Java

Java Socket通信中怎样进行心跳检测

小樊
82
2024-10-16 18:28:20
栏目: 编程语言

在Java Socket通信中,进行心跳检测的目的是为了保持连接的活跃状态,防止因为长时间不通信导致的连接被客户端或服务器端主动关闭。下面是一个简单的心跳检测示例:

  1. 服务器端:
import java.io.*;
import java.net.*;
import java.util.concurrent.*;

public class Server {
    public static void main(String[] args) throws IOException, InterruptedException {
        int port = 12345;
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        ServerSocket serverSocket = new ServerSocket(port);

        while (true) {
            Socket clientSocket = serverSocket.accept();
            executorService.submit(() -> handleClient(clientSocket));
        }
    }

    private static void handleClient(Socket clientSocket) {
        try {
            InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            PrintWriter writer = new PrintWriter(outputStream, true);

            String heartBeatMessage = "HEARTBEAT";
            while (true) {
                // 发送心跳包
                writer.println(heartBeatMessage);
                Thread.sleep(5000); // 每5秒发送一次心跳包

                // 读取客户端返回的消息
                String message = reader.readLine();
                if (message != null && message.equals(heartBeatMessage)) {
                    // 收到客户端的心跳包,回应一个确认消息
                    writer.println("HEARTBEAT_ACK");
                } else {
                    // 没有收到心跳包,关闭连接
                    break;
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  1. 客户端:
import java.io.*;
import java.net.*;
import java.util.concurrent.*;

public class Client {
    public static void main(String[] args) throws IOException, InterruptedException {
        String serverAddress = "localhost";
        int port = 12345;
        Socket socket = new Socket(serverAddress, port);
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        // 启动一个线程定期发送心跳包
        executorService.submit(() -> sendHeartBeat(socket));

        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String message;
        while ((message = reader.readLine()) != null) {
            System.out.println("Received from server: " + message);
            if (message.equals("HEARTBEAT_ACK")) {
                // 收到服务器的确认消息,继续发送心跳包
                sendHeartBeat(socket);
            }
        }
    }

    private static void sendHeartBeat(Socket socket) throws IOException, InterruptedException {
        OutputStream outputStream = socket.getOutputStream();
        PrintWriter writer = new PrintWriter(outputStream, true);
        String heartBeatMessage = "HEARTBEAT";
        while (true) {
            // 发送心跳包
            writer.println(heartBeatMessage);
            Thread.sleep(5000); // 每5秒发送一次心跳包
        }
    }
}

在这个示例中,服务器端和客户端都会定期发送心跳包,以保持连接的活跃状态。如果一方在一段时间内没有收到心跳包,它会认为连接已经断开,并关闭连接。

0
看了该问题的人还看了