我正在创建一个聊天服务器程序,我使用了这里编写的代码 http://makemobiapps.blogspot.com/p/multiple-client-server-chat-programming.html 我想在其中添加一些更改,我试图让服务器向所有连接的客户端发送消息。我已经添加了这段代码。但它不起作用。它将消息发送给客户端,但方式不正确,就像它只将消息发送给一个客户端一样。然后它停止接受任何客户端连接到网络。
这是我使用扫描仪添加的代码
while (true) {
try {
int i = 0;
clientSocket = serverSocket.accept();
for (i = 0; i < maxClientsCount; i++) {
if (threads[i] == null) {
(threads[i] = new clientThread(clientSocket, threads)).start();
break;
}
}
// this my code I add to broadcast a message to all clients
if(!in.nextLine().isEmpty() ){
for (i = 0; i < maxClientsCount; i++) {
PrintStream os = new PrintStream(clientSocket.getOutputStream());
os.println("Server :"+in.next());
}
}
if (i == maxClientsCount) {
PrintStream os = new PrintStream(clientSocket.getOutputStream());
os.println("Server too busy. Try later.");
os.close();
clientSocket.close();
}
}
catch (IOException e) {
System.out.println(e);
}
请知道这对我有帮助:) 谢谢
最佳答案
for (i = 0; i < maxClientsCount; i++) {
这里您在 0 和 maxClientsCount
之间循环 i
。
PrintStream os = new PrintStream(clientSocket.getOutputStream());
在这里,您正在写入最近接受的套接字,maxClientsCount-1
次,并完全忽略i
。
os.println("Server :"+in.next());
在这里,您每次循环都会从扫描仪
读取一个新 token 。
这没有多大意义。当然你的意思是:
String line = in.nextLine();
if(!line.isEmpty() ){
for (i = 0; i < maxClientsCount; i++) {
if (threads[i] == null)
continue;
PrintStream os = new PrintStream(threads[i].getSocket().getOutputStream());
os.println("Server :"+line);
}
}
关于java - java中从服务器向多个客户端发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47979173/