简体   繁体   中英

What's the use of offset while reading from NetworkStream?

I wrote a simple echo server with sockets. While making it I found that these two code gives the same result.

  var buffer = new byte[bytesToRead];
        var bytesRead = 0;
        while (bytesRead < bytesToRead)
        {
            var bytesReceived = await networkStream.ReadAsync(buffer, 0, (bytesToRead - bytesRead))
                .ConfigureAwait(false);
            if (bytesReceived == 0)
                throw new Exception("Socket Closed");
            bytesRead += bytesReceived;
        }

        return buffer;

 var buffer = new byte[bytesToRead];
        var bytesRead = 0;
        while (bytesRead < bytesToRead)
        {
            var bytesReceived = await networkStream.ReadAsync(buffer, bytesRead, (bytesToRead - bytesRead))
                .ConfigureAwait(false);
            if (bytesReceived == 0)
                throw new Exception("Socket Closed");
            bytesRead += bytesReceived;
        }

        return buffer;

The difference is in one I always set the

offset=0

while on the other I set

offset=bytesRead

(offset is 2nd parameter of networkStream.ReadAsync(byte[] buffer, int offset ,int count) ).

So what I concluded is that it doesn't matter what's the offset is as both code works but then how these both codes are working?

does offset is ignored in network stream?

As mentioned in the comments, In stream the second parameter is the offset into the buffer array not the stream That means if you keep the offset 0 then your are overwriting the buffer. Also network stream does not allow seeking. And I was getting same results because I was trying this on very short message length, in which case the loop effectively runs a single iteration to read the entire message, so the 2 code snippets appear to give the same result. I tried it on a much longer message and results changes.

So, the correct way is the second way in which I used offset as bytesRead.

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