Java 使用 Socket 判断某服务能否连通

业务场景:判断socket server在否在线,在线返回true,不在线返回false

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;
    }
}

 

posted @ 2019-10-18 14:35  农名工进城  阅读(637)  评论(0编辑  收藏  举报