java-no.10 socket processing InputStream input stream

Source: Internet
Author: User

When creating a socket using the InputStream input stream, the read () method, if the call is available (), returns the length of the byte stream, may return 0, or other numeric values, often error in network operation, Because when you call the available () method, the data sent to the send may not yet arrive, and the count you get is 0.

     Network transmission is implemented as follows:

int readbytes = 0;  byte[] buffer = new byte[1024];// 1024 can be changed to any required value   int len = buffer.length;while  (Readbytes < len)  {    int read = inputstream.read (Buffer, readbytes, len  - readbytes);       //determines whether the data stream is read at the end of the &nbsp, preventing a dead loop.       if  (read == -1 | |  read <  (len - readbytes)  {         readbytes += read;     break;    }     if (read ==  (len - readbytes))  {         byte[] tmpbuffer = new byte[len * 2];         system.arraycopy (buffer, 0, tmpbuffer, 0, buffer.length);         buffer = tmpbuffer;    len =  Buffer.length;    }      readbytes += read;} byte[] endodeddata = new byte[readbytes]; System.arraycopy (buffer, 0, endodeddata, 0, readbytes); System.out.println (endodeddata.length);


java-no.10 socket processing InputStream input stream

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.