gpt4 book ai didi

java - 多线程 Socket 通讯 Client/Server

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:04:09 27 4
gpt4 key购买 nike

我完成了一个运行良好的客户端/服务器套接字通信程序。现在我想弄清楚如何做到这一点,以便我可以同时拥有到服务器的多个客户端连接。我环顾四周,似乎有不止几种不同的方法可以做到这一点。所以我来这里是想向你们寻求帮助/建议。

我的服务器:

public class Server {
private ServerSocket serverSocket = null;
private Socket clientSocket = null;

public Server() {
try {
serverSocket = new ServerSocket(7003);
} catch (IOException e) {
System.err.println("Could not listen on port: 7003");
System.exit(1);
}

try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed");
System.exit(1);
}
}

public void startServer() throws IOException {
PrintWriter output = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

String inputLine, outputLine;

outputLine = "Connected to Server";
output.println(outputLine);

while ((inputLine = input.readLine()) != null) {
// This just determines users input and server ruturns output based on that

outputLine = this.getServerOutput(inputLine);
output.println(outputLine);

if (outputLine.equals("Bye"))
break;
}

output.close();
input.close();
clientSocket.close();
serverSocket.close();
}
}

我需要让我的构造函数创建线程和 startServer() 还是我的运行方法?

最佳答案

您应该使用 ExecutorService。您的客户端请求处理将是 Runnablerun() 并且在每次接受之后您可以调用 ExecutorService.submit(runnableTask) 以异步服务客户端。

使用 ExecutorService 的示例。

public class MyServer {

private static MyServer server;
private ServerSocket serverSocket;

/**
* This executor service has 10 threads.
* So it means your server can process max 10 concurrent requests.
*/
private ExecutorService executorService = Executors.newFixedThreadPool(10);

public static void main(String[] args) throws IOException {
server = new MyServer();
server.runServer();
}

private void runServer() {
int serverPort = 8085;
try {
System.out.println("Starting Server");
serverSocket = new ServerSocket(serverPort);

while(true) {
System.out.println("Waiting for request");
try {
Socket s = serverSocket.accept();
System.out.println("Processing request");
executorService.submit(new ServiceRequest(s));
} catch(IOException ioe) {
System.out.println("Error accepting connection");
ioe.printStackTrace();
}
}
}catch(IOException e) {
System.out.println("Error starting Server on "+serverPort);
e.printStackTrace();
}
}

//Call the method when you want to stop your server
private void stopServer() {
//Stop the executor service.
executorService.shutdownNow();
try {
//Stop accepting requests.
serverSocket.close();
} catch (IOException e) {
System.out.println("Error in server shutdown");
e.printStackTrace();
}
System.exit(0);
}

class ServiceRequest implements Runnable {

private Socket socket;

public ServiceRequest(Socket connection) {
this.socket = connection;
}

public void run() {

//Do your logic here. You have the `socket` available to read/write data.

//Make sure to close
try {
socket.close();
}catch(IOException ioe) {
System.out.println("Error closing client connection");
}
}
}
}

关于java - 多线程 Socket 通讯 Client/Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12588476/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com