以下是接受客戶端套接字連接併爲每個連接分配線程的代碼(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是的,先生。 –