下面是接受客户端套接字连接并为每个连接分配线程的代码(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
条件下探测它,这样你的处理线程将能够优雅地完成工作。
您可以通过使用线程id作为键
将Threads
存储到线程安全映射(因为它将由多个线程并发访问)来做到这一点// Map that will contain all my threads
Map<Long, ClientServiceThread> threads = new ConcurrentHashMap<>();
// Add to the constructor the instance of the class that manage the threads
ClientServiceThread cliThread = new ClientServiceThread(this, clientSocket);
// Add my new thread
threads.put(cliThread.getId(), cliThread);
cliThread.start();
当一个击杀被发射时
String clientCommand = in.readLine().toLowerCase();
if (clientCommand.startsWith("kill")) {
main.interrupt(Long.valueOf(clientCommand.substring(4).trim()));
}
然后在主类中你的方法看起来像:
public void interrupt(long threadId) {
// Remove the thread from the map
ClientServiceThread cliThread = threads.remove(threadId);
if (cliThread != null) {
// Interrupt the thread
cliThread.interrupt();
}
}
最后,您需要使您的类ClientServiceThread
对中断敏感
try {
...
while (!Thread.currentThread().isInterrupted()) {
// My code here
}
} finally {
clientSocket.close();
}
终止循环:
while (running) {
String clientCommand = in .readLine();
if (clientCommand.equalsIgnoreCase("Kill")) {
running = false;
}
}
或:
while (running) {
String clientCommand = in .readLine();
if (clientCommand.equalsIgnoreCase("Kill")) {
break;
}
}
不要忘记关闭finally
块中的套接字
要停止当前线程,请关闭套接字,并从run()方法返回:
if (clientCommand.equalsIgnoreCase("Kill")) {
clientSocket.close();
return;
}
编辑:要关闭另一个线程,您可以,例如,
- 在线程之间共享一个线程安全的clientID-Thread表。当一个新客户端连接时,您将为该客户端启动的线程存储在这个映射 中
- 当Kill-client1命令进入时,您从映射中获得对应"client1"键的线程,并在该线程上调用ìnterrupt()。
- 中的每个线程(例如,client1线程),在循环的每次迭代中,检查thread . currentthread (). isinterrupted()的值。如果为真,则关闭连接,从共享映射中删除线程,并从
run()
方法返回。