java的客户端服务端Socket通信完整实例(心跳包,客户端断线重连,服务端超时断开客户端连接)代码
时间: 2023-11-03 15:04:15 浏览: 111
Socket-master.rar
好的,下面是一个简单的 Java 客户端服务端 Socket 通信的完整实例,包括心跳包、客户端断线重连、服务端超时断开客户端连接的代码:
客户端代码:
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Client {
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
private boolean connected = false;
public void connect(String host, int port) {
try {
socket = new Socket(host, port);
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
connected = true;
System.out.println("Connected to " + host + ":" + port);
} catch (IOException e) {
System.err.println("Failed to connect to " + host + ":" + port);
}
}
public void disconnect() {
try {
if (socket != null && !socket.isClosed()) {
socket.close();
inputStream.close();
outputStream.close();
connected = false;
System.out.println("Disconnected from server");
}
} catch (IOException e) {
System.err.println("Failed to disconnect from server");
}
}
public void send(String message) {
try {
outputStream.write(message.getBytes());
outputStream.flush();
} catch (IOException e) {
System.err.println("Failed to send message");
}
}
public void startHeartbeat() {
Thread heartbeatThread = new Thread(() -> {
while (connected) {
send("heartbeat");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.err.println("Heartbeat thread interrupted");
}
}
});
heartbeatThread.start();
}
public void startReconnect() {
Thread reconnectThread = new Thread(() -> {
while (!connected) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.err.println("Reconnect thread interrupted");
}
System.out.println("Attempting to reconnect...");
connect("localhost", 1234); // replace with actual host and port
}
});
reconnectThread.start();
}
public void listen() {
Thread listenThread = new Thread(() -> {
byte[] buffer = new byte[1024];
while (connected) {
try {
int bytesRead = inputStream.read(buffer);
if (bytesRead > 0) {
String message = new String(buffer, 0, bytesRead);
System.out.println("Received message: " + message);
}
} catch (IOException e) {
System.err.println("Failed to read message");
disconnect();
}
}
});
listenThread.start();
}
public static void main(String[] args) {
Client client = new Client();
client.connect("localhost", 1234); // replace with actual host and port
client.startHeartbeat();
client.startReconnect();
client.listen();
}
}
```
服务端代码:
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private ServerSocket serverSocket;
private boolean running = false;
public void start(int port) {
try {
serverSocket = new ServerSocket(port);
running = true;
System.out.println("Server started on port " + port);
while (running) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress());
handleClient(clientSocket);
}
} catch (IOException e) {
System.err.println("Failed to start server");
}
}
public void stop() {
try {
if (serverSocket != null && !serverSocket.isClosed()) {
serverSocket.close();
running = false;
System.out.println("Server stopped");
}
} catch (IOException e) {
System.err.println("Failed to stop server");
}
}
private void handleClient(Socket clientSocket) {
Thread clientThread = new Thread(() -> {
try {
InputStream inputStream = clientSocket.getInputStream();
OutputStream outputStream = clientSocket.getOutputStream();
byte[] buffer = new byte[1024];
while (true) {
int bytesRead = inputStream.read(buffer);
if (bytesRead > 0) {
String message = new String(buffer, 0, bytesRead);
System.out.println("Received message from client: " + message);
if (message.equals("heartbeat")) {
continue;
}
outputStream.write(("You said: " + message).getBytes());
outputStream.flush();
}
}
} catch (IOException e) {
System.err.println("Failed to handle client");
} finally {
try {
clientSocket.close();
System.out.println("Client disconnected: " + clientSocket.getInetAddress().getHostAddress());
} catch (IOException e) {
System.err.println("Failed to close client socket");
}
}
});
clientThread.start();
}
public static void main(String[] args) {
Server server = new Server();
server.start(1234); // replace with actual port
}
}
```
在客户端代码中,`connect()` 方法用于连接服务器,`disconnect()` 方法用于断开连接,`send()` 方法用于发送消息,`startHeartbeat()` 方法用于启动心跳包发送线程,`startReconnect()` 方法用于启动断线重连线程,`listen()` 方法用于启动消息接收线程。在服务端代码中,`start()` 方法用于启动服务器,`stop()` 方法用于停止服务器,`handleClient()` 方法用于处理客户端连接。注意在客户端代码中,心跳包的发送间隔为 5 秒,断线重连的间隔也为 5 秒,这些时间间隔可以根据实际情况进行调整。
阅读全文