简体   繁体   中英

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?

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.

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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM