如下只是通过判断端口通不通来大体了解服务的状态,并不能用这个准确判断某服务的实际运行状态。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55package com.iaiot.utils;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
/**
* SocketUtils
*
* @author iaiot
*/
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, 1000);
}
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;
}
}