91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

如何在Java Socket中實現多線程通信

小樊
83
2024-09-02 22:10:20
欄目: 編程語言

在Java Socket中實現多線程通信,可以使用線程池來管理多個客戶端連接。這里是一個簡單的示例,展示了如何使用Java Socket和多線程實現服務器與多個客戶端之間的通信。

  1. 首先,創建一個處理客戶端請求的Runnable類:
import java.io.*;
import java.net.Socket;

public class ClientHandler implements Runnable {
    private final Socket clientSocket;

    public ClientHandler(Socket clientSocket) {
        this.clientSocket = clientSocket;
    }

    @Override
    public void run() {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
             PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println("Received from client: " + inputLine);
                out.println("Server received: " + inputLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  1. 然后,創建一個服務器類,用于監聽客戶端連接并將每個連接分配給一個新的線程:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MultiThreadedServer {
    public static void main(String[] args) {
        int port = 8080;
        ExecutorService executorService = Executors.newFixedThreadPool(10); // 創建一個固定大小的線程池

        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Server started on port: " + port);

            while (true) {
                Socket clientSocket = serverSocket.accept(); // 接受客戶端連接
                System.out.println("New client connected: " + clientSocket.getInetAddress());

                ClientHandler clientHandler = new ClientHandler(clientSocket);
                executorService.submit(clientHandler); // 將客戶端處理任務提交給線程池
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown(); // 關閉線程池
        }
    }
}
  1. 最后,創建一個客戶端類,用于與服務器進行通信:
import java.io.*;
import java.net.Socket;

public class Client {
    public static void main(String[] args) {
        String hostname = "localhost";
        int port = 8080;

        try (Socket socket = new Socket(hostname, port);
             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
             BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {
            System.out.println("Connected to server");

            new Thread(() -> {
                try {
                    String serverMsg;
                    while ((serverMsg = in.readLine()) != null) {
                        System.out.println("Server: " + serverMsg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();

            String userInput;
            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

現在,你可以運行服務器類和多個客戶端類實例,它們將能夠通過多線程通信。注意,這個示例僅用于演示目的,實際應用中需要考慮更多的錯誤處理和資源管理。

0
兰考县| 吉安县| 巴南区| 伊金霍洛旗| 临湘市| 商水县| 驻马店市| 台湾省| 聂拉木县| 连云港市| 安泽县| 汨罗市| 平遥县| 惠州市| 庆城县| 通州区| 常熟市| 东莞市| 达日县| 阳曲县| 东乡县| 潢川县| 钟祥市| 老河口市| 天等县| 黎川县| 资溪县| 界首市| 京山县| 赤壁市| 天台县| 皋兰县| 平凉市| 益阳市| 阿克| 丰都县| 松溪县| 务川| 渝中区| 江源县| 华池县|