Three ways to solve read blocking in Java socket long connections

  • 2020-04-01 03:24:07
  • OfStack

There are three solutions:

1 the Length of the data to be sent, such as HTTP keepAlive, must depend on this content-length
2 set the timeout time. In my experience, this is only valid at the Socket level.

Socket socket = new Socket(host,port);
socket.setSoTimeout(100); // If more than 100 Thrown if there is no data for milliseconds SocketTimeoutException

Close the connection after the sending end has sent the data. This is very common for Http operations.

(how does an InputStream tell if the data has been read?)

In some cases where you can't change the client, case one just passes away, case two is relatively good, and when you block, you throw an exception. Case 3 is not suitable for a long connection, because the link cannot be interrupted during the entire communication process and the shutdown cannot be completed. There's a fourth way: stop reading when you get to some character, like break when you get to byebye. But this also requires changing the client code. A compromise was chosen to set the 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);

Related articles: