温馨提示×

java socket如何实现多线程通信

小樊
133
2024-06-27 18:15:28
栏目: 编程语言

在Java中,可以通过多线程来实现Socket通信。下面是一个简单的示例代码,演示了如何使用多线程实现Socket通信:

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

public class MultiThreadedServer {

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(12345);
            System.out.println("Server started. Listening for connections on port 12345...");

            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("Connection received from " + clientSocket.getInetAddress().getHostAddress());

                ClientHandler clientHandler = new ClientHandler(clientSocket);
                Thread clientThread = new Thread(clientHandler);
                clientThread.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class ClientHandler implements Runnable {
        private 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();
            }
        }
    }
}

在这个示例中,ServerSocket在端口12345上监听客户端连接。一旦有连接建立,就会创建一个新的ClientHandler线程来处理该连接。ClientHandler类实现了Runnable接口,用于处理客户端的输入和输出。

在ClientHandler线程中,我们创建了一个BufferedReader来读取客户端发送的消息,并通过PrintWriter来向客户端发送消息。循环读取客户端发送的消息,直到客户端关闭连接。

这样,通过多线程的方式,我们可以实现Socket通信,并同时处理多个客户端的连接。

0