There are 3 solutions:
1 Agree on the length of data to be sent. For example, keepAlive of http must rely on this Content-Length.
2 Set the timeout time. According to my experience, it is only effective if set at the Socket level.
Copy the code as follows: Socket socket = new Socket(host,port);
socket.setSoTimeout(100); // If there is no data for more than 100 milliseconds, throw SocketTimeoutException
3. After the sender has finished sending the data, close the connection. This is very common in HTTP operations.
(How does InputStream determine that the data has been read)
Sometimes, when the client cannot be modified, the first situation will only pass. The second situation is relatively more suitable. When blocked, an exception will be thrown directly. Scenario 3 is not suitable for long connections because the link cannot be interrupted during the entire communication process, nor can it be shut down to end. In fact, there is a fourth method: when certain characters are read, stop reading. For example, when byebye is read, break. But this also requires changing the client code. I chose a compromise - setting a timeout:
StringBuilder sb = new StringBuilder();try { client.setSoTimeout(500); while ((a = client.getInputStream().read(buf)) != -1) { sb.append(new String(buf, 0, a)); if (a != size) { break; } }} catch (Exception e) {}System.out.println(sb);