recv() 套接字函数返回长度为 0 的数据 [英] recv() socket function returning data with length as 0

查看:62
本文介绍了recv() 套接字函数返回长度为 0 的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,它在端口号 5005 上与另一台设备(带有 Web 服务器的硬件设备)建立了套接字连接.

I am having an application which established a socket connection on a port number 5005 with another device(hardware device with a web server).

现在,如果我的硬件设备断开连接,那么我与设备的连接就会断开.

Now if my hardware device disconnects then i loose connection with the device.

  1. 这是否意味着我的套接字使用到现在无效.

  1. Does this mean that the socket i was using until now becomes invalid.

我有没有收到什么特别的信息,比如空字符或什么时候这种断开发生了.

Do i get any special message like null character or something when this disconnect happens.

谢谢

推荐答案

recv 返回值 0 时,表示连接已关闭.

When recv returns a value of 0 that means the connection has been closed.

请参阅recv 手册页:

See the recv man page:

这些调用返回接收到的字节数,如果有错误则返回-1发生了.对等端执行有序后返回值为 0关闭.

These calls return the number of bytes received, or -1 if an error occurred. The return value will be 0 when the peer has performed an orderly shutdown.

在回答问题 #1 时,是的,套接字现在无效.您必须创建一个新的套接字和连接以进行进一步的通信.

In answer to question #1, yes the socket is now invalid. You must create a new socket and connection for further communications.

编辑

现在正如 valdo 在下面指出的那样,也有可能有一个半关闭的 TCP 连接,在这种连接中您无法再接收任何信息,但您可以继续写入套接字,直到您完成发送数据.有关更多详细信息,请参阅此文章:TCP 半关闭.不过,您似乎没有这种情况.

Now as valdo pointed out below, there is also the possibility of having a half-closed TCP connection in which you can't receive any more but you can keep writing to the socket until you've finished sending your data. See this article for more details: TCP Half-Close. It doesn't sound like you have this situation though.

在回答问题#2 时,基本上有两种方法可以检测关闭的套接字.这假设套接字经历了有序关闭,这意味着对等方调用了 shutdownclose.

In answer to question #2, there are basically two ways to detect a closed socket. This assumes that the socket went through an orderly shutdown, meaning the peer called either shutdown or close.

第一种方法是从套接字读取,在这种情况下,返回值为 0.另一种方法是写入套接字,这将导致抛出 SIG_PIPE 信号,指示管道损坏.

The first method is to read from the socket in which case you get a return value of 0. The other method is to write to the socket, which will cause the SIG_PIPE signal to be thrown indicating a broken pipe.

为了避免信号,您可以设置 MSG_NOSIGNAL 套接字选项,在这种情况下 send 将返回 -1 并将 errno 设置为 EPIPE.

In order to avoid the signal, you can set the MSG_NOSIGNAL socket option in which case send would return -1 and set errno to EPIPE.

这篇关于recv() 套接字函数返回长度为 0 的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆