亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

如何在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
象山县| 子洲县| 通州市| 阿拉善左旗| 延寿县| 长葛市| 武乡县| 江山市| 桐柏县| 东阳市| 吴江市| 松江区| 土默特右旗| 崇州市| 花垣县| 进贤县| 全椒县| 康保县| 青海省| 吴堡县| 闸北区| 镇原县| 黄浦区| 玉门市| 建昌县| 扶绥县| 永平县| 芷江| 廊坊市| 光泽县| 拉孜县| 玛纳斯县| 河津市| 岑溪市| 安陆市| 涪陵区| 武隆县| 梁平县| 无棣县| 巢湖市| 乌拉特中旗|