Java Socket 服务端:心跳机制实现客户端连接和数据收发
以下是一个简单的 Java Socket 服务端示例,使用心跳机制接收客户端连接,并进行数据收发。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static final int PORT = 8888; // 服务端口号
private static final int HEARTBEAT_INTERVAL = 5000; // 心跳间隔时间,单位为毫秒
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
// 创建 ServerSocket 实例,并绑定端口号
serverSocket = new ServerSocket(PORT);
System.out.println('Server started on port ' + PORT);
while (true) {
// 接收客户端连接
clientSocket = serverSocket.accept();
System.out.println('Client connected: ' + clientSocket.getRemoteSocketAddress());
// 开启心跳线程
new HeartbeatThread(clientSocket).start();
// 创建输入输出流
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// 循环接收和发送数据
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println('Received from client ' + clientSocket.getRemoteSocketAddress() + ': ' + inputLine);
out.println('Server received: ' + inputLine);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (clientSocket != null) {
clientSocket.close();
}
if (serverSocket != null) {
serverSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 心跳线程
private static class HeartbeatThread extends Thread {
private Socket clientSocket;
public HeartbeatThread(Socket clientSocket) {
this.clientSocket = clientSocket;
}
@Override
public void run() {
try {
while (true) {
Thread.sleep(HEARTBEAT_INTERVAL);
clientSocket.getOutputStream().write(0);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
}
在上面的示例中,我们首先创建了一个 ServerSocket 实例,并绑定了端口号。然后我们进入一个无限循环,不断接收客户端连接。
在接收到客户端连接后,我们首先开启了一个心跳线程,用来定时向客户端发送心跳包。然后我们创建了输入输出流,用来接收和发送数据。
在接收到客户端的数据后,我们将数据打印出来,并将处理后的数据发送回客户端。
最后,我们在程序结束时关闭输入输出流和客户端连接。
原文地址: https://www.cveoy.top/t/topic/n9bc 著作权归作者所有。请勿转载和采集!