开发者

socket behavior on read

the client writes 5 bytes to the socket after every 1 second. the server continuously reads from the socket. the buffer at the server end is 10 bytes long. so the function looks like this

 read(fd, buf, 10);

the server reads 5 bytes everytime.

now the client writes 5 bytes continuously. the server is the same. the server reads 10 bytes everytime.

so is it that the read on a socket returns as many bytes as available in the buffer. it does not wait to fill up the buffer.

does it have something to do with SO_RCVLOWAT. i read t开发者_C百科hat this socket option only has an effect in select/poll io.

thanks

update:

i changed SO_RCVLOWAT to 10, now it waits for 10 bytes at least in the receive buffer. so it seems it does have something to do with the low water mark of the receive buffer.

but i cannot set the low watermark to 0. it always sets it to 1 in that case. why is it so?


The 10 I believe is actually the length of the buffer, so the read will read up to 10 bytes but might not get everything in there or it may not fill it up. I believe it actually returns the number of bytes written to the buffer.

No, it will not typically wait until the buffer is full to return.


If you have not set nonblocking I/O then the read() call will wait until all the bytes you requested are available or there was an error on the socket.

If you do set nonblocking I/O then there is no guarantee that you will even get 5 bytes - you might get one read with 2 and one with 6 -- it depends on the system and network timing.


If you want to fill the 10 bytes buffer, you can set SO_RCVLOWAT to 10 and it should work just fine.

poll/select will signal a socket as readable even if there are not SO_RCVLOWAT bytes available (at least on linux). If you intend to use your socket with poll/select, be aware that a call read/recv/etc... after poll/select might block until SO_RCVLOWAT number of bytes are available.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜