我必须将数据推送到服务器,如何检查服务器是否正常并使用java从特定端口接受数据
谢谢
答案 0 :(得分:-1)
您可以使用此方法(使用套接字):
public static boolean checkServerAvailability(String host, int port, int timeout) {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port), timeout);
return true;
} catch (IOException e) {
return false; // time is out , or the server is unreachable
}
}
如果服务器远程
,您可以使用此功能boolean reachable = InetAddress.getByName(hostname or IP).isReachable();
您也可以使用HTTP
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("HEAD");
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
// there is a problem with connection
}