怎樣通過Java Socket實(shí)現(xiàn)多線程通信

小樊
82
2024-10-16 18:25:19
欄目: 編程語言

在Java中,使用Socket結(jié)合多線程可以實(shí)現(xiàn)客戶端和服務(wù)器之間的多線程通信。下面是一個(gè)簡(jiǎn)單的示例,展示了如何使用Java Socket實(shí)現(xiàn)多線程通信。

服務(wù)器端代碼:

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); // 創(chuàng)建一個(gè)固定大小的線程池

        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("Server is listening on port " + port);

        while (true) {
            Socket clientSocket = serverSocket.accept();
            executorService.execute(new ClientHandler(clientSocket)); // 將客戶端連接交給線程池處理
        }
    }
}

class ClientHandler implements Runnable {
    private Socket clientSocket;

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

    @Override
    public void run() {
        try {
            InputStream inputStream = clientSocket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            String message;
            while ((message = reader.readLine()) != null) {
                System.out.println("Received from client: " + message);

                // 發(fā)送響應(yīng)給客戶端
                OutputStream outputStream = clientSocket.getOutputStream();
                PrintWriter writer = new PrintWriter(outputStream, true);
                writer.println("Server response: " + message);
            }

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

客戶端代碼:

import java.io.*;
import java.net.*;

public class Client {
    public static void main(String[] args) throws IOException {
        String serverAddress = "localhost";
        int port = 12345;

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

        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

        // 發(fā)送消息給服務(wù)器
        writer.println("Hello, Server!");
        System.out.println("Sent message to server");

        // 讀取服務(wù)器的響應(yīng)
        String response = reader.readLine();
        System.out.println("Received from server: " + response);

        socket.close();
    }
}

在這個(gè)示例中,服務(wù)器使用了一個(gè)固定大小的線程池來處理客戶端連接。當(dāng)服務(wù)器接收到一個(gè)新的客戶端連接時(shí),它會(huì)將這個(gè)連接交給線程池中的一個(gè)線程來處理。這樣可以確保服務(wù)器能夠同時(shí)處理多個(gè)客戶端連接,而不會(huì)因?yàn)樘幚韱蝹€(gè)連接而阻塞其他連接。

客戶端通過Socket連接到服務(wù)器,并發(fā)送一條消息給服務(wù)器。服務(wù)器接收到消息后,會(huì)將其原樣返回給客戶端??蛻舳嗽诮邮盏椒?wù)器的響應(yīng)后,關(guān)閉與服務(wù)器的連接。

0