这篇文章主要介绍了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; } }原文链接:https://www.f2er.com/java/526441.html