溫馨提示×

java socket如何實現(xiàn)心跳機(jī)制

小樊
223
2024-06-27 18:22:29
欄目: 編程語言

在Java中,可以使用Socket來實現(xiàn)心跳機(jī)制,通過在客戶端和服務(wù)器端發(fā)送和接收心跳包來保持連接的活躍性。以下是一個簡單的示例代碼來實現(xiàn)心跳機(jī)制:

客戶端代碼:

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

public class Client {

    public static void main(String[] args) {
        String serverAddress = "127.0.0.1";
        int serverPort = 8888;

        try {
            Socket socket = new Socket(serverAddress, serverPort);
            OutputStream outputStream = socket.getOutputStream();

            while (true) {
                // 發(fā)送心跳包
                String heartbeatMsg = "heartbeat";
                outputStream.write(heartbeatMsg.getBytes());
                outputStream.flush();

                Thread.sleep(5000); // 每隔5秒發(fā)送一次心跳包
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

服務(wù)器端代碼:

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    public static void main(String[] args) {
        int serverPort = 8888;

        try {
            ServerSocket serverSocket = new ServerSocket(serverPort);
            System.out.println("Server started...");

            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("Client connected: " + socket.getInetAddress());

                InputStream inputStream = socket.getInputStream();
                byte[] buffer = new byte[1024];

                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    String msg = new String(buffer, 0, len);
                    System.out.println("Received message: " + msg);

                    // 判斷是否為心跳包
                    if (msg.equals("heartbeat")) {
                        System.out.println("Received heartbeat from client");
                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上面的示例代碼中,客戶端在循環(huán)中每隔5秒發(fā)送一次心跳包給服務(wù)器,服務(wù)器接收到心跳包后進(jìn)行判斷并輸出相關(guān)信息。通過這種方式可以實現(xiàn)簡單的心跳機(jī)制來保持連接的活躍性。

0