Java – socket input stream is hung at the end of reading What’s the best way?

I'm a little obsessed with how to avoid my socket hanging on reading This is my code:

Socket socket = new Socket("someMachine",16003);
    OutputStream outputStream = socket.getOutputStream();
    InputStream inputStream = socket.getInputStream();
    try {
        outputStream.write(messageBuffer.toByteArray());
        outputStream.flush();
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer response = new StringBuffer();
        int result;
        while ((result = in.read()) != -1) {
            response.append(Character.tochars(result));
            System.out.println(result);
        }
        System.out.println("Done!");  //never gets printed
     } catch (...) {}

The above code successfully reads all data in the stream, but it will hang Reading online, I expect to receive a - 1 from the server (I can't control) to indicate that I have reached the end of the stream, but I get this:

(Lots of data above this point)
57
10
37
37
69
79
70
10

Then hang up, so my question is:

1) Do I have a coding error or a problem with the server's response?

2) If there is a problem with the server's response (that is, it does not return - 1), how can I solve this problem (that is, hang when reading is stopped)

Any help appreciated!

Solution

The problem with hanging as long as reading is stopped is that this can happen in two situations:

1: The server has no more data to send

2: The server has sent more data, but your client has not received it due to network overload

You only want to really stop reading in the first case, but you want to block reading in the second case

The solution to this problem is to develop a transport protocol (standard) that allows the server to tell customers how much data it expects to send

If the server knows the total data size in advance, just start by sending the total number of bytes in the transmission, and then send the data The client knows when to receive all data

(or the server can simply close the connection after completion, so that the reading fails, but only when the connection is not needed in the future.)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>