因此,現在我正在製作基於客戶端服務器的應用程序多線程。在服務器端,我創建了一個可以接受的單一連接的線程。向所有客戶端發送消息(客戶端 - 服務器通信)
在線程類中,我製作了一個將命令發送給客戶端的方法。我只想要的是,如何向所有正在運行的客戶端發送參數?對於簡單的陳述,我只是想讓這臺服務器向所有連接的客戶端發送消息。
我已閱讀this post並從this link找到sendToAll(String message)
方法。但是當我嘗試使用我的代碼時,在ServerSocket
中沒有類似的方法。
好吧,這是我的服務器和線程的示例代碼。
class ServerOne{
ServerSocket server = null;
...
ServerOne(int port){
System.out.println("Starting server on port "+port);
try{
server = new ServerSocket(port);
System.out.println("Server started successfully and now waiting for client");
} catch (IOException e) {
System.out.println("Could not listen on port "+port);
System.exit(-1);
}
}
public void listenSocket(){
while(true){
ClientWorker w;
try{
w = new ClientWorker(server.accept());
Thread t = new Thread(w);
t.start();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
}
}
protected void finalize(){
try{
server.close();
} catch (IOException e) {
System.out.println("Could not close socket");
System.exit(-1);
}
}
}
class ClientWorker implements Runnable{
Socket client;
ClientWorker(Socket client){
this.client = client;
}
public void run(){
...
sendCommand(parameter);
...
}
public void sendCommand(String command){
PrintWriter out = null;
try {
out = new PrintWriter(client.getOutputStream(), true);
out.println(command);
} catch (IOException ex) {}
}
}
感謝您的幫助:)
你的答案是偉大的,但你缺乏一些冒號和你應該改變'messages.dequeue();'和'messages.enqueue();''來messages.take();'和' messages.put();' – Danon
另外,你確定這個類是線程安全的嗎?我的意思是,如果在accept/threads更改clientList時調用sendToOne()/ sendToAll會怎樣? – Danon
@Danon請參閱編輯。 – Mordechai