java socket长连接心跳检测代码
时间: 2023-10-31 21:03:45 浏览: 85
下面是一个简单的Java Socket长连接心跳检测代码示例:
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class SocketClient {
public static void main(String[] args) {
String host = "localhost";
int port = 8080;
try {
Socket socket = new Socket(host, port);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
while (true) {
// 发送心跳包
out.write("ping".getBytes());
out.flush();
// 等待服务器响应
byte[] buffer = new byte[1024];
int len = in.read(buffer);
if (len == -1) {
System.out.println("Server closed connection.");
break;
}
String response = new String(buffer, 0, len);
if ("pong".equals(response)) {
System.out.println("Received pong from server.");
} else {
System.out.println("Received unknown response from server: " + response);
}
// 等待一段时间再次发送心跳包
Thread.sleep(5000);
}
} catch (IOException e) {
System.out.println("Error connecting to server: " + e.getMessage());
} catch (InterruptedException e) {
System.out.println("InterruptedException occurred: " + e.getMessage());
}
}
}
```
在这个示例中,客户端向服务器发送一个字符串"ping"作为心跳包,然后等待服务器响应。如果服务器响应了"pong",客户端会打印出"Received pong from server.",否则会打印出"Received unknown response from server:" 加上收到的响应内容。在等待一段时间(这里是5000毫秒)之后,客户端会再次发送心跳包。如果服务器关闭了连接,客户端会退出循环并打印出"Server closed connection."。
阅读全文
相关推荐


















