tags:

views:

52

answers:

3

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?

+2  A: 

I think Java NIO non-blocking classes are your best choice. Check SocketChannel class and its related code samples.

But be careful, when you issue your read command, it might be the case that bytes are not available yet, but that doesn't mean that the will never arrive to your socket...

Pablo Santa Cruz
+1  A: 

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.

SB
A: 

If the input ends before supplying two bytes it will throw EOFException. If there is no input available() will return zero, although it can also return zero if there is input in some circumstances (e.g. SSL).

EJP