BufferedReader blocking at read()

喜欢而已 提交于 2019-12-06 04:59:36

The end of stream on the receiver side isn't reached until the sending stream (or entire socket) is closed.

output.close() on the send side will cause the receive side to see end of stream.

If you need to use the stream for multiple messages, you'll need to introduce a frame structure in to your application protocol so that receiver can determine message boundaries. This can be as simple as prefixing the length of the message in bytes to each message.

Since you are using a String as your entire message. You can use DataInputStream and DataOutputStream stream decorators to frame the message for you with readUTF() and writeUTF(String). writeUTF(String) basically frames the string by writing its length to stream before writing the string. readUTF() then reads this length and then knows how much data it needs to read off the stream before returning.

Example:

Output:

DataOutputStream output = new DataOutputStream(connection.getOutputStream());

private void sendMessage(String message) {
    displayMessage(message);

    try {
        output.writeUTF(message);
        output.flush();
    } catch (IOException e) {
        System.out.println("IO ex at sendMessage client");
    }

}

Input:

DataInputStream input = new DataInputStream(connection.getInputStream());

String message = input.readUTF();

serverDispaly(message);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!