Ivan Kuckir
Ivan Kuckir

Reputation: 2549

Read bytes from socket in Java

I have a Socket in Java (java.net.ServerSocket). I read from it using InputStream.

I would like to read several bytes from socket, when they are available. So I use InputStream.read(bytes, 0, num).

It works fine when I test it locally (over 127.0.0.1). But when I put it on internet and connect to it, it reads only 2916 bytes. How can I read exactly "num" bytes and don't continue, unitl I receive them?

Upvotes: 1

Views: 3105

Answers (2)

SKi
SKi

Reputation: 8466

That is the way how readings of sockets usually works. When using slower 'network' than loopback, all data is not transferred immediately.

read(bytes, 0, num) will return when there is data available. There may be one or more bytes, even more than num bytes available. num only limits how much data is moved to bytes array.

So if you want to receive excatly num bytes, then you must call read again. Of cource with smaller len and bigger off parameters.

Example:

    int offset = 0;
    int wanted = buffer.length;

    while( wanted > 0 )
    {
        final int len = istream.read( buffer, offset, wanted );     
        if( len == -1 )
        {
            throw new java.io.EOFException( "Connection closed gracefully by peer" );
        }
        wanted -= len;
        offset += len;
    }

Upvotes: 2

Blueberry
Blueberry

Reputation: 2231

Sounds like something to do with the way your network is set up. Something else could be sending data to it. Have you tried using a different port?

If that doesn't work, try disabling your network connection / disconnecting from your network to see if its something from outside which is actually causing the problem.

Upvotes: 2

Related Questions