/**
* 判断网络是否连通
*
* @return
*/
public boolean testNetConnect(String ip, int port) {
if (DpUtil.isBlank(ip)) {
return false;
}
Socket connect = new Socket();
try {
//建立连接
connect.connect(new InetSocketAddress(ip, port), timeout);
//通过现有方法查看连通状态
boolean res = connect.isConnected();
logger.debug("网络连通");
return res;
} catch (IOException e) {
logger.info("网络断开" + ip + ":" + port);
return false;
} finally {
try {
connect.close();
} catch (IOException e) {
logger.error("网络断开,关闭socket异常" + ip + ":" + port);
}
}
}
Java实战小技巧(三):检测网络连接状况(代码示例)
最新推荐文章于 2024-04-29 14:08:23 发布