现在,我正在制作一个基于多线程的客户端服务器应用程序。在服务器端,我为每个接受到的连接创建一个线程。
在线程类中,我编写了一个向客户端发送命令的方法。我想知道的是,如何将参数发送给所有正在运行的客户端?简单来说,我只想让这个服务器向所有连接的客户端发送一条消息。
我已经阅读了此帖子并从此链接找到了
好的,这是我的服务器和线程的示例代码。
在线程类中,我编写了一个向客户端发送命令的方法。我想知道的是,如何将参数发送给所有正在运行的客户端?简单来说,我只想让这个服务器向所有连接的客户端发送一条消息。
我已经阅读了此帖子并从此链接找到了
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