java - java中从服务器向多个客户端发送消息

标签 java multithreading sockets synchronization client-server

我正在创建一个聊天服务器程序,我使用了这里编写的代码 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/

相关文章:

java - BufferedReader 在用 java 读取我的文件时跳过每一行

c++ - 使用线程的段错误

java - 使用多线程将文本文件拆分为Java中的 block

android - android中的NsdChat套接字连接异常

java - Pycharm - 内部启动问题 -java.lang.RuntimeException : Could not find installation home path

java - 从部分 XML 向 TableLayout 添加更多行

多线程情况下的Java设计模式: Factory vs Singleton?

C# 套接字模型 View 控件

node.js - 与 socket.io 和 uci 下棋

java - 如何在 ubuntu 14.04 x64 上使用 subclipse 和 eclipse kepler?