【问题标题】:Cannot send messages to all clients无法向所有客户端发送消息
【发布时间】:2016-05-25 09:57:28
【问题描述】:

我想从服务器向所有客户端发送消息。

我的方法是创建一个当前连接到服务器的所有客户端的 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();
        }
    }   
}

关于我可能在哪里做错的任何建议?
感谢您的宝贵时间。

【问题讨论】:

    标签: java networking client-server chat


    【解决方案1】:
    • 你不能混合println()readUTF().readUTF()唯一能理解的是writeUTF().写的数据
    • 您需要在套接字的整个生命周期内使用相同的流或读取器/写入器。

    【讨论】:

    • 我在哪里混合 println() 和 readUTF?你指的是 System.out.println(message)?
    【解决方案2】:

    您正在写入 OutputStream 但没有刷新它们。

     for(Socket s:socs)
     {
          System.out.println(message);
          DataOutputStream toClient=newDataOutputStream(s.getOutputStream());
          toClient.writeUTF(message);
          toClient.flush();
     }
    

    您还必须确保服务器正在从 socketNew 套接字接收任何消息。因为它可能会在等待在线输入时被阻塞:

    message=fromClient.readUTF();
    

    顺便说一句,为每条消息创建新的 DataOutputStream 并不是一个好方法。

    【讨论】:

    • 我冲洗了它,但没有用。你能告诉我一些替代方法吗?
    • 查看我答案的后半部分。你确定你收到消息。尝试替换 message=fromClient.readUTF();带有一些示例消息,例如 message = "foo";
    • DataOutputStreams 不需要刷新,除非下面有一个BufferedOutputStream,这里没有。
    猜你喜欢
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    相关资源
    最近更新 更多