Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Sockets nonblocking read

Tags:

java

sockets

I'm using a DataInputStream to read characters/data from a socket.

I want to use .readUnsignedShort(); and have it throw an exception if there isn't 2 bytes to read. Should I subclass the DataInputStream and override the methods adding the exceptions, or is there an easier way?

like image 737
clarity Avatar asked Sep 08 '26 09:09

clarity


1 Answers

If you want something quick and dirty, try inputStream.available().

if (stream.available() < 2) {
    // throw it
}

If you want true non blocking reads and callbacks when data is available, I think Pablo's answer is better.

like image 126
NG. Avatar answered Sep 09 '26 21:09

NG.