在网络编程中,使用Socket进行多线程编程是非常常见的,可以实现服务器和多个客户端之间的通信。下面是一个简单的Java示例,演示了如何使用Socket进行多线程编程。

```java

import java.io.*;

import java.net.*;

public class MultiThreadedServer {

public static void main(String[] args) {

int portNumber = 8888;

ServerSocket serverSocket = null;

try {

serverSocket = new ServerSocket(portNumber);

System.out.println("MultiThreadedServer started on port " portNumber);

while (true) {

Socket clientSocket = serverSocket.accept();

System.out.println("New client connected: " clientSocket);

ClientHandler clientHandler = new ClientHandler(clientSocket);

Thread clientThread = new Thread(clientHandler);

clientThread.start();

}

} catch (IOException e) {

System.err.println("Could not listen on port " portNumber);

System.exit(1);

} finally {

try {

if (serverSocket != null) {

serverSocket.close();

}

} catch (IOException e) {

System.err.println("Error closing server socket");

}

}

}

}

class ClientHandler implements Runnable {

private Socket clientSocket;

public ClientHandler(Socket socket) {

this.clientSocket = socket;

}

public void run() {

try (

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

) {

String inputLine;

while ((inputLine = in.readLine()) != null) {

System.out.println("Received from client: " inputLine);

out.println("Echo from server: " inputLine);

}

} catch (IOException e) {

System.err.println("Error handling client");

} finally {

try {

clientSocket.close();

} catch (IOException e) {

System.err.println("Error closing client socket");

}

}

}

}

```

在这个示例中,主服务器使用ServerSocket监听指定端口,当有新的客户端连接时,会创建一个新的ClientHandler线程来处理该客户端的请求。每个ClientHandler线程负责与对应客户端的通信。当客户端发送消息时,服务器会回复相同的消息,并在控制台上打印接收到的消息。

这个示例演示了使用Socket和多线程技术实现简单的多客户端服务器,你可以根据实际需求来扩展和优化这个示例。

免责声明:本网站部分内容由用户自行上传,若侵犯了您的权益,请联系我们处理,谢谢!联系QQ:2760375052 沪ICP备2023024866号-10

分享:

扫一扫在手机阅读、分享本文

评论