【问题标题】:One Client just listening after a few messages: Client Server Chat with ArrayList sockets outputstreamwriter一个客户端只是在听几条消息后:Client Server Chat with ArrayList sockets outputstreamwriter
【发布时间】:2015-09-27 01:20:02
【问题描述】:

我的广播方法有问题。我与服务器和客户端进行了聊天。每个客户端运行一个线程并有一个用于输出流的自己的套接字一开始一切正常,但在几条消息之后,只有一个客户端可以发送,而另一个客户端只能接收消息..?!我不知道为什么有人有想法?一开始都可以发送和接收.. 我无法关闭输出流,因为那时我得到了一个空指针异常,但也许这是错误? 感谢您的每一次帮助!

服务器:

public static void broadcastJSON(JSONObject jsonObject, ArrayList<Socket> socketList)throws IOException{

        OutputStreamWriter out = null;
        for(int i=0; i<socketList.size(); i++){
            out=new OutputStreamWriter(socketList.get(i).getOutputStream(), "UTF-8");
            out.write(jsonObject.toString() + "\n");
            out.flush();
        }
    }

客户:

public JSONObject receiveJSON()throws IOException{
        BufferedReader in = new BufferedReader(new InputStreamReader(Client.socket.getInputStream(), "UTF-8"));
        String obje = in.readLine();
        JSONObject jsonObject = new JSONObject(obje);
        return jsonObject;
}

【问题讨论】:

    标签: multithreading sockets server chat outputstream


    【解决方案1】:

    BufferedReader. 正在丢失预读数据,不要为每条消息创建新的流/读取器/写入器。在插座的整个生命周期内使用相同的。

    【讨论】:

    • 好的,我会试试的,谢谢!我之前想过。在收到的消息中应该是可能的,但是当我必须为 socketList 中的每个特定套接字流式传输时,我该如何在广播方法中做到这一点。谢谢您的回复!
    猜你喜欢
    • 2023-03-04
    • 2019-05-05
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2022-01-21
    相关资源
    最近更新 更多