anzure

Test#getResponseTime

Mar 28th, 2016
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.98 KB | None | 0 0
  1. package net.hydrotekz.NetMonitor.pingers.MC;
  2.  
  3. import java.net.InetAddress;
  4. import java.net.InetSocketAddress;
  5. import java.nio.channels.SocketChannel;
  6.  
  7. public class Test {
  8.  
  9.     public static long getResponseTime(String hostAddress, int port) {
  10.         InetAddress inetAddress = null;
  11.         InetSocketAddress socketAddress = null;
  12.         SocketChannel sc = null;
  13.         long timeToRespond = -1;
  14.         long start, stop;
  15.  
  16.         try {
  17.             inetAddress = InetAddress.getByName(hostAddress);
  18.             socketAddress = new InetSocketAddress(inetAddress, port);
  19.  
  20.             // Open the channel, set it to non-blocking, initiate connect
  21.             sc = SocketChannel.open();
  22.             sc.configureBlocking(true);
  23.             start = System.nanoTime();
  24.             if (sc.connect(socketAddress)) {
  25.                 stop = System.nanoTime();
  26.                 timeToRespond = (stop - start)/1000000;
  27.             }
  28.  
  29.         } catch (Exception e){
  30.             // Quiet error
  31.  
  32.         } finally {
  33.             try {
  34.                 if (sc != null) sc.close();
  35.             } catch (Exception e) {
  36.                 // Quiet error
  37.             }
  38.         }
  39.         return timeToRespond;
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment