gpt4 book ai didi

JAVA 多线程服务器套接字

转载 作者:行者123 更新时间:2023-11-30 08:32:47 25 4
gpt4 key购买 nike

以下是接受客户端套接字连接并为每个连接分配一个线程的代码 (JAVA)。

 ServerSocket m_ServerSocket = new ServerSocket();

while (true) {
java.util.Date today = Calendar.getInstance().getTime();
System.out.println(today+" - Listening to new connections...");

Socket clientSocket = m_ServerSocket.accept();
ClientServiceThread cliThread = new ClientServiceThread( clientSocket);
cliThread.start();
}

假设有 5 个客户端连接,因此有 5 个线程在运行。

client 1: threadId 11
client 2: threadId 12
client 3 :threadId 13
client 4 :threadId 14
client 5 :threadId 15

假设其中一个客户端发送消息“kill-client1”,我希望结束客户端 1 的连接并终止 ID 为 11 的线程,如下所示:

public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));

while (running) {
String clientCommand = in .readLine();

if (clientCommand.equalsIgnoreCase("Kill-client1")) {
// end the connection for client 1 & kill it's corresponding thread 11
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

我怎样才能做到这一点?

最佳答案

只需跟踪所有客户端套接字和/或处理线程。

Map<Integer,Socket> clients=new HashMap<>();

while (true) {
java.util.Date today = Calendar.getInstance().getTime();
System.out.println(today+" - Listening to new connections...");

Socket clientSocket = m_ServerSocket.accept();
clients.put(generateNewClientId(),clientSocket);
ClientServiceThread cliThread = new ClientServiceThread( clientSocket);
cliThread.start();
}

然后如果你只是做

{
if (clientCommand.equalsIgnoreCase("Kill")) {
Socket socket=clients.get(idToShutDown);// get required id somehow (from request??)
socket.close();
}
}

这将关闭给定的套接字,导致在处理线程时中断 in.readLine() 从而完成线程。

如果您跟踪线程,您可以设置“中断”标志并在 while 条件下探测它,以便您的处理线程能够优雅地完成工作。

关于JAVA 多线程服务器套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39871742/

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