uahakan uahakan - 2 years ago 79
Java Question

"available" of DataInputStream from Socket

I have this code on the client side :

DataInputStream dis = new DataInputStream(socketChannel.socket().getInputStream());

keeps returning
, although there is readable data in the stream. So after the actual data to be read is finished, empty data is passed to the other class to be read and this causes corruption.

After a little search; I found that
is not reliable when using with sockets, and that I should be reading first few bytes from stream to actually see if data is available to parse.

But in my case; I have to pass the
reference I get from the socket to some other class that I cannot change.

Is it possible to read a few bytes from
without corrupting it, or any other suggestions ?

Answer Source

Putting a PushbackInputStream in between allows you to read some bytes without corrupting the data.

EDIT: Untested code example below. This is from memory.

static class MyWrapper extends PushbackInputStream {
    MyWrapper(InputStream in) {

    public int available() throws IOException {
        int b =;
        // do something specific?
        return super.available();

public static void main(String... args) {
    InputStream originalSocketStream = null;
    DataInputStream dis = new DataInputStream(new MyWrapper(originalSocketStream));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download