Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // TEST OK
- // 參考 https://crunchify.com/in-java-jow-to-check-if-socket-is-alive-and-connection-is-active-on-specific-port-issocketalive-utility/
- private static boolean testConn(String hostName, int port)
- {
- boolean isAlive = false;
- SocketAddress socketAddress = new InetSocketAddress(hostName, port);
- Socket socket = new Socket();
- // 單位:milliseconds
- int timeout = 3000; //3,000 ms = 3 sec
- try {
- socket.connect(socketAddress, timeout);
- //socket.close();
- isAlive = true;
- } catch (SocketTimeoutException exception) {
- System.out.println("testConn SocketTimeoutException " + hostName + ":" + port + ". " + exception.getMessage());
- } catch (IOException exception) {
- System.out.println(
- "testConn IOException - Unable to connect to " + hostName + ":" + port + ". " + exception.getMessage());
- }finally{
- try {
- socket.close();
- } catch (IOException e) {
- System.out.println("testConn socket close fail");
- }
- }
- return isAlive;
- }
Advertisement
Add Comment
Please, Sign In to add comment