3 ways to resolve read blocking in Java socket long connection _java

Source: Internet
Author: User

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);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.