UNIX 套接字:如何检查 TCP 流是否已关闭以供读取或 EOF?
我正在编写一个简单的客户端,它通过 TCP 流读取二进制数据。 由于文件是逐部分发送的,因此我有一个与此类似的循环:
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;
...
}
读取是通过 recv() 方法完成的,该方法返回收到的字节数。 这个想法显然是只要打开 TCP 流就读取数据,但似乎上述方法对我不起作用。
还有其他想法吗?在流关闭或遇到 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 clean 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果套接字正确关闭,
recv()
返回 0;如果出现错误,则返回 -1。因此,您将一直读取直到recv()
返回<=0
。您发布的代码片段看起来是正确的 - 为什么您认为它不适合您?发生了什么,你期待什么?如果您的套接字是非阻塞的,您还必须处理
recv()
返回 -1 且errno
设置为EAGAIN
的情况或EWOULDBLOCK
。这意味着套接字仍然有效,但现在没有更多数据。recv()
returns 0 if the socket was properly closed, -1 if there was an error. So, you read untilrecv()
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 anderrno
is set toEAGAIN
orEWOULDBLOCK
. This means that the socket is still alive and well, but there's no more data right now.