UNIX 套接字:如何检查 TCP 流是否已关闭以供读取或 EOF?

发布于 2024-11-01 08:43:04 字数 441 浏览 0 评论 0原文

我正在编写一个简单的客户端,它通过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜是你 2024-11-08 08:43:04

如果套接字正确关闭,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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文