Java uses socket to determine whether a service can connect to a code instance

This article mainly introduces how Java uses socket to judge whether a service can be connected. The example code is introduced in great detail, which has certain reference value for everyone's study or work. Friends in need can refer to it

Business scenario: judge whether the socket server is online, return true if it is online, and return false if it is not online

package com.thinkgem.wlw.modules.test.socketdemo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.socket;
import java.net.socketAddress;
import java.net.socketTimeoutException;
import java.net.UnkNownHostException;
/**
 * @Author zhouhe
 * @Date 2019/10/18 14:24
 */
public class SocketUtils {
  /**
   * 判断某服务能否连通
   *
   * @param host host
   * @param port port
   * @return boolean
   */
  public static boolean isRunning(String host,int port) {
    Socket sClient = null;
    try {
      SocketAddress saAdd = new InetSocketAddress(host.trim(),port);
      sClient = new Socket();
      sClient.connect(saAdd,3000);  //设置超时 3s
    }
    catch (UnkNownHostException e) {
      return false;
    }
    catch (SocketTimeoutException e) {
      return false;
    }
    catch (IOException e) {
      return false;
    }
    catch (Exception e) {
      return false;
    }
    finally {
      try {
        if (sClient != null) {
          sClient.close();
        }
      }
      catch (Exception e) {
      }
    }
    return true;
  }
}

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>