There are 3 ways to solve this problem:
1 agreed to send the data length, such as HTTP keepAlive is to rely on this content-length
2 set timeout time, according to my experience, only at the socket level settings are valid.
Copy Code code as follows:
Socket socket = new socket (host,port);
Socket.setsotimeout (100); If there is no data for more than 100 milliseconds, throw the Sockettimeoutexception
3 Let the sender finish sending the data, close the connection. This is common when working with HTTP.
(InputStream How to determine that the data has been read end)
Sometimes when the client cannot be modified, the case is only pass off, the situation is relatively suitable, when blocking directly throw an exception. Situation three is not suitable for long connection, because the entire communication process link is not interrupted, also cannot adjust shutdown end. In fact, there is a fourth way: when reading to some characters are not read down, such as reading to Byebye on the break. But this also needs to change the client code. A compromise was chosen-set timeout:
StringBuilder sb = new StringBuilder ();
try {
client.setsotimeout ();
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);