长连接java代码
时间: 2023-07-26 20:03:39 浏览: 139
Java 长链接示例
以下是一个在 Java 中实现长连接的简单示例代码:
```
import java.io.*;
import java.net.*;
public class LongConnectionClient {
private static final String SERVER_HOST = "localhost";
private static final int SERVER_PORT = 8080;
private static final int CONNECTION_TIMEOUT = 5000;
private static final int HEARTBEAT_INTERVAL = 10000;
public static void main(String[] args) {
try {
Socket socket = new Socket();
socket.setSoTimeout(CONNECTION_TIMEOUT);
socket.connect(new InetSocketAddress(SERVER_HOST, SERVER_PORT));
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// 发送心跳消息
new Thread(new Runnable() {
public void run() {
try {
while (true) {
Thread.sleep(HEARTBEAT_INTERVAL);
writer.write("heartbeat\n");
writer.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
// 接收消息
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这段代码实现了一个长连接的客户端,通过 Socket 连接服务器,并维护心跳和数据传输。在心跳线程中,每隔一段时间发送一个心跳消息;在消息接收循环中,不断接收服务器发送的消息并输出。需要注意的是,在实际应用中还需要对异常和错误进行处理,并根据具体的业务逻辑实现消息的解析和处理。
阅读全文