基于java的Socket通信完整实例(心跳包,客户端断线重连,服务端超时断开客户端连接)
时间: 2024-02-23 11:00:44 浏览: 68
C# socket通信项目,实现了实现了心跳、断线重连、服务端异步接收数据、消息回调反馈、解决了粘包相关问题,可以多客户端
5星 · 资源好评率100%
好的,下面是一个基于Java的Socket通信完整实例,包括心跳包、客户端断线重连和服务端超时断开客户端连接的处理。
服务端代码:
```java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("Server started, waiting for client...");
// 设置超时时间为5秒
serverSocket.setSoTimeout(5000);
while (true) {
try {
Socket socket = serverSocket.accept();
System.out.println("Client connected: " + socket.getRemoteSocketAddress());
// 新建线程处理客户端请求
new Thread(new RequestHandler(socket)).start();
} catch (IOException e) {
System.out.println("Server timeout, no client connected.");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
客户端代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
public class Client {
private static final String HOST = "localhost";
private static final int PORT = 8888;
private static final int HEARTBEAT_INTERVAL = 5000; // 心跳包发送间隔
private static final int RECONNECT_INTERVAL = 5000; // 断线重连间隔
private static final int SERVER_TIMEOUT = 15000; // 服务端超时时间
private Socket socket;
private BufferedReader reader;
private OutputStreamWriter writer;
private boolean connected = false;
public void start() {
while (true) {
try {
if (!connected) {
connect();
}
if (connected) {
// 发送心跳包
writer.write("heartbeat\n");
writer.flush();
// 等待服务器响应
String response = reader.readLine();
if (response != null) {
System.out.println("Server response: " + response);
}
}
} catch (SocketException e) {
System.out.println("Connection lost.");
connected = false;
} catch (IOException e) {
e.printStackTrace();
}
// 休眠一段时间后重试连接
try {
Thread.sleep(RECONNECT_INTERVAL);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void connect() {
try {
socket = new Socket(HOST, PORT);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new OutputStreamWriter(socket.getOutputStream());
// 设置超时时间为15秒
socket.setSoTimeout(SERVER_TIMEOUT);
System.out.println("Connected to server.");
connected = true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("Server not available.");
}
}
public static void main(String[] args) {
new Client().start();
}
}
```
RequestHandler代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class RequestHandler implements Runnable {
private Socket socket;
private BufferedReader reader;
private OutputStreamWriter writer;
public RequestHandler(Socket socket) {
this.socket = socket;
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new OutputStreamWriter(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
while (true) {
String request = reader.readLine();
if (request != null) {
System.out.println("Received request from client: " + request);
// 处理心跳包请求
if (request.equals("heartbeat")) {
writer.write("heartbeat\n");
writer.flush();
}
}
}
} catch (IOException e) {
System.out.println("Client disconnected: " + socket.getRemoteSocketAddress());
} finally {
try {
reader.close();
writer.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
这个实例中,客户端每隔5秒向服务端发送一个心跳包请求,服务端收到请求后返回一个响应。如果客户端在超时时间内没有收到服务器的响应,则认为服务器没有响应,断开连接并尝试重连。如果服务端在超时时间内没有收到客户端的请求,则认为客户端已经断开连接,关闭连接并等待下一个客户端连接。
阅读全文