java - Read all byte from InputStream -


i want asynchronously read bytes inputstream of active tcp connection. there nothing in inputbuffer, in case want empty byte array[] , not read/timeout.

i tried this:

byte[] bytes = ioutils.tobytearray(tcpinputstream); 

but if there nothing in inputstream read hangs until tcp timeout , exception thrown.

you can use non blocking socketchannels:

import java.net.inetsocketaddress; import java.nio.bytebuffer; import java.nio.channels.socketchannel;  ...  socketchannel socketchannel = socketchannel.open(); socketchannel.connect(new inetsocketaddress("127.0.0.1", 80)); bytebuffer buffer = bytebuffer.allocate(2048); int bytesread; while ((bytesread = socketchannel.read(buffer)) >= 0) {     if (bytesread == 0)         thread.sleep(1000); // usefull stuff     else {         // use bytes , prepare buffer next read         buffer.clear();     } } socketchannel.close(); 

also prepare ioexception when server closes connection.


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -