recv()套接字函数返回长度为0的数据 [英] recv() socket function returning data with length as 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.
-
这是否意味着套接字i是
使用直到现在变得无效。
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,基本上有两种方法来检测一个关闭的套接字。这假设套接字通过有序关闭,意味着对等体调用 shutdown
或 close
。
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
套接字选项 发送
将返回-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屋!