优秀是一种习惯!!!
Solo  当前访客:2 开始使用

AmethystFOB

记录精彩人生

单端口多任务多线程长链接加心跳监测CS示例

2024-08-01 10:51:39 amethystfob
0  评论    0  浏览

服务端代码示例

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicBoolean;

public class SocketServer {

    public static void main(String[] args) {
        int port = 9999; // 设置服务器端口

        try {
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("Socket Server is running on port " + port);

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

                // 使用线程处理客户端请求
                ClientHandler clientHandler = new ClientHandler(socket);
                clientHandler.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static class ClientHandler extends Thread {
        private Socket socket;
        private AtomicBoolean running;

        public ClientHandler(Socket socket) {
            this.socket = socket;
            this.running = new AtomicBoolean(true);
        }

        @Override
        public void run() {
            try {
                BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter output = new PrintWriter(socket.getOutputStream(), true);

                // 开始处理心跳
                startHeartbeat(output);

                while (running.get()) {
                    String request = input.readLine();
                    if (request == null) {
                        break;
                    }
                    System.out.println("Received request: " + request);

                    String response = processRequest(request);
                    output.println(response);
                }

                // 关闭资源
                socket.close();
                System.out.println("Connection closed");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        private void startHeartbeat(PrintWriter output) {
            Thread heartbeatThread = new Thread(() -> {
                while (running.get()) {
                    try {
                        // 发送心跳消息到客户端
                        output.println("heartbeat");
                        Thread.sleep(5000); // 每隔5秒发送一次心跳
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            heartbeatThread.start();
        }

        private String processRequest(String request) {
            // 根据请求内容处理不同的任务
            if (request.equalsIgnoreCase("task1")) {
                return "Response from task 1";
            } else if (request.equalsIgnoreCase("task2")) {
                return "Response from task 2";
            } else {
                return "Unknown request";
            }
        }

        public void shutdown() {
            running.set(false);
        }
    }
}

客户端代码示例

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class SocketClient {

    public static void main(String[] args) {
        String serverAddress = "localhost"; // 服务器地址
        int port = 9999; // 服务器端口

        try {
            Socket socket = new Socket(serverAddress, port);
            System.out.println("Connected to server on port " + port);

            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter output = new PrintWriter(socket.getOutputStream(), true);

            // 启动一个线程来接收服务器的响应
            Thread responseThread = new Thread(() -> {
                try {
                    while (true) {
                        String response = input.readLine();
                        if (response == null) {
                            break;
                        }
                        System.out.println("Server response: " + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            responseThread.start();

            // 模拟发送请求到服务器
            output.println("task1");
            Thread.sleep(1000); // 等待1秒
            output.println("task2");

            // 模拟长时间运行的客户端程序
            Thread.sleep(60000); // 休眠60秒,模拟长时间运行

            // 关闭连接
            socket.close();
            System.out.println("Connection closed");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

示例说明

  1. 服务端代码

    • SocketServer 类负责监听客户端连接,并为每个客户端创建一个 ClientHandler 线程来处理通信。
    • ClientHandler 类实现了心跳机制和请求处理。心跳机制通过一个单独的线程定期向客户端发送心跳消息。
  2. 客户端代码

    • SocketClient 类连接到指定的服务器地址和端口,并启动一个线程来接收服务器的响应。
    • 客户端通过向服务器发送不同的请求(例如:"task1" 和 "task2")来模拟通信过程。
    • 通过 Thread.sleep() 来模拟客户端长时间运行的情况。

这些示例代码展示了如何实现基于Java的Socket通信,并加入心跳机制以维持长连接的活跃性。在实际应用中,可以根据具体需求进一步扩展和优化。


标题:单端口多任务多线程长链接加心跳监测CS示例
作者:amethystfob
地址:https://newmoon.top/articles/2024/08/01/1722480699350.html

欢迎各路大侠指点留痕:



      Open Mind, Open Sight

目录

TOP