以下是接受客户端套接字连接并为每个连接分配线程的代码(JAVA)。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
假设一个客户端发送消息“杀 - 客户端1”,我希望最终客户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();
}
}
我怎样才能做到这一点?
所以你basicly想为客户能够杀死其他客户端:) – Antoniossss
@Antoniossss是的,先生。 –