UNIX sockets: How to check if TCP stream is closed for reading or EOF?
I am writing a simple client which reads binary data through a TCP stream. Since the file is sent part-by-part I have a loop similar to this one:
while (1 /* Maybe a check for EOF or if the socket is closed here ? */) {
ssize_t bytes_red = recv(
if (bytes_read <= 0) // not working properly ?
break;
...
}
The reading is done via recv() method, which returns the number of bytes received. The idea is obviously to read data as long the TCP stream is opened, but it seems the above approach does not work for me.
Any other ideas? What is a cl开发者_如何学运维ean way to read from socket until the stream is closed or EOF is encountered?
EDIT: The above approach works fine, I had a bug elsewhere.
recv()
returns 0 if the socket was properly closed, -1 if there was an error. So, you read until recv()
returns <=0
. Your posted code snippet looks correct - why do you think it's not working for you? What happens, what did you expect?
If your socket is non-blocking, you will also have to handle the case where recv()
returns -1 and errno
is set to EAGAIN
or EWOULDBLOCK
. This means that the socket is still alive and well, but there's no more data right now.
精彩评论