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
Post a Comment