我想从服务器向所有客户端发送消息。
我的方法是创建一个当前连接服务器的所有客户端的ArrayList。 如果任何客户端发送消息,我会遍历 ArrayList 并向每个客户端发送消息。
问题是我的客户没有收到任何消息。
这是我在服务器端的发送方法:
private void message() {
while (true) {
DataInputStream fromClient;
try {
fromClient = new DataInputStream(socketNew.getInputStream());
message = fromClient.readUTF();
for (Socket s:socs) {
System.out.println(message);
DataOutputStream toClient = newDataOutputStream( s.getOutputStream() );
toClient.writeUTF(message);
}
message="";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这是我在客户端的接收方法:
private void receive_data() {
{
DataInputStream fromServer;
try {
fromServer = new DataInputStream(socket.getInputStream());
message = fromServer.readUTF();
console(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
关于我可能做错的地方有什么建议吗?
感谢您抽出时间。
最佳答案
- 不能混合使用
println()
和readUTF()。
readUTF()
唯一能理解的是由writeUTF()。
- 您需要在套接字的生命周期内使用相同的流或读取器/写入器。
关于java - 无法向所有客户端发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35393302/