I'm really sorry if my question is a duplicate, but I didn't find useful infos in the site.
如果我的问题是重复的,我真的很抱歉,但是我在网站上找不到有用的信息。
I'm using non blocking sockets and a select(). How can I detect if a client closed the connection on non-blocking socket? I saw that a read() returns -1 with errno = EWOULDBLOCK when no datas are available to be read and also when a connection is closed.
我正在使用非阻塞套接字和一个select()。如何检测客户端是否关闭了非阻塞套接字上的连接?我看到一个read()返回-1和errno = ewill dblock,当没有数据可以读取时,也当连接关闭时。
How can I discriminate above cases?
我怎样才能区分上述情况?
2 个解决方案
#1
2
When the peer has closed the connection:
当对等点已关闭连接:
-
select()
will return the socket as readable. - select()将返回可读的套接字。
- A
recv()
orread()
on the socket will return zero. - 套接字上的recv()或read()将返回0。
I saw that a read() returns -1 with errno = EWOULDBLOCK when no datas are available to be read
我看到read()返回-1,当没有可用的数据可以读取时,errno = eif dblock
Correct, but the connection isn't closed.
正确,但是连接没有关闭。
and also when a connection is closed.
当连接被关闭时。
No you didn't. That's not correct. It returns zero.
不,你没有。这是不正确的。它返回0。
How can I discriminate above cases?
我怎样才能区分上述情况?
They aren't the same, and they don't manifest themselves in the same way.
他们不一样,他们不以同样的方式表现自己。
#2
0
When the peer had closed the connection for a specific socket, a call to read()
on this socket would return 0
. This behaviour is independent from the socket's blocking state.
当对等点关闭特定套接字的连接时,该套接字上的read()调用将返回0。这种行为独立于套接字的阻塞状态。
From man 2 read
(italics by me):
从男人2读(斜体由我):
RETURN VALUE
返回值
On success, the number of bytes read is returned (zero indicates end of file)
在成功时,读取的字节数被返回(0表示文件结束)
#1
2
When the peer has closed the connection:
当对等点已关闭连接:
-
select()
will return the socket as readable. - select()将返回可读的套接字。
- A
recv()
orread()
on the socket will return zero. - 套接字上的recv()或read()将返回0。
I saw that a read() returns -1 with errno = EWOULDBLOCK when no datas are available to be read
我看到read()返回-1,当没有可用的数据可以读取时,errno = eif dblock
Correct, but the connection isn't closed.
正确,但是连接没有关闭。
and also when a connection is closed.
当连接被关闭时。
No you didn't. That's not correct. It returns zero.
不,你没有。这是不正确的。它返回0。
How can I discriminate above cases?
我怎样才能区分上述情况?
They aren't the same, and they don't manifest themselves in the same way.
他们不一样,他们不以同样的方式表现自己。
#2
0
When the peer had closed the connection for a specific socket, a call to read()
on this socket would return 0
. This behaviour is independent from the socket's blocking state.
当对等点关闭特定套接字的连接时,该套接字上的read()调用将返回0。这种行为独立于套接字的阻塞状态。
From man 2 read
(italics by me):
从男人2读(斜体由我):
RETURN VALUE
返回值
On success, the number of bytes read is returned (zero indicates end of file)
在成功时,读取的字节数被返回(0表示文件结束)