Guest User

Untitled

a guest
Nov 13th, 2021
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1.   // TEST OK
  2. // 參考 https://crunchify.com/in-java-jow-to-check-if-socket-is-alive-and-connection-is-active-on-specific-port-issocketalive-utility/
  3.  
  4.     private static boolean testConn(String hostName, int port)
  5.  
  6.     {
  7.  
  8.         boolean isAlive = false;
  9.  
  10.        
  11.  
  12.         SocketAddress socketAddress = new InetSocketAddress(hostName, port);
  13.  
  14.         Socket socket = new Socket();
  15.  
  16.  
  17.         // 單位:milliseconds
  18.  
  19.         int timeout = 3000; //3,000 ms = 3 sec
  20.  
  21.  
  22.         try {
  23.  
  24.             socket.connect(socketAddress, timeout);
  25.  
  26.             //socket.close();
  27.  
  28.             isAlive = true;
  29.  
  30.  
  31.         } catch (SocketTimeoutException exception) {
  32.  
  33.             System.out.println("testConn SocketTimeoutException " + hostName + ":" + port + ". " + exception.getMessage());
  34.  
  35.         } catch (IOException exception) {
  36.  
  37.             System.out.println(
  38.  
  39.                     "testConn IOException - Unable to connect to " + hostName + ":" + port + ". " + exception.getMessage());
  40.  
  41.         }finally{
  42.  
  43.             try {
  44.  
  45.                 socket.close();
  46.  
  47.             } catch (IOException e) {
  48.  
  49.                 System.out.println("testConn socket close fail");
  50.  
  51.             }
  52.  
  53.         }  
  54.  
  55.         return isAlive;
  56.  
  57.     }
Advertisement
Add Comment
Please, Sign In to add comment