本文介绍了`sock.recv()` 当连接在非阻塞套接字上死机时返回空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 中有一个名为 sock 的非阻塞套接字.根据我的理解,如果连接已被对等方关闭,recv() 方法应该引发异常,但它返回一个空字符串 ('') 而我不不知道为什么.

I have a non-blocking socket in Python called sock. According to my understanding the recv() method should raise an exception if the connection has been closed by the peer, but it returns an empty string ('') and I don't know why.

这是我测试的脚本(来自 此处):

This is the script I test with (from here):

import sys
import socket
import fcntl, os
import errno
from time import sleep

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
fcntl.fcntl(s, fcntl.F_SETFL, os.O_NONBLOCK)

while True:
    try:
        msg = s.recv(4096)
        print("got data '{msg}'".format(msg=msg))
    except socket.error, e:
        err = e.args[0]
        if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
            sleep(1)
            print 'No data available'
            continue
        sys.exit(1)

如果对端关闭连接,这个套接字应该在 recv() 上引发 socket.error,但它只返回 ''>.

If the peer closes the connection this socket is supposed to raise socket.error on recv(), but instead it only returns ''.

我是这样测试的,使用两个终端:

I test it this way, using two terminals:

# Terminal 1
~$ nc -l -p9999

# Terminal 2
~$ python ./test_script.py

# Terminal 1
typingsomestring

# Terminal 2
No data available
No data available
No data available
got data 'typingsomestring
'
No data available
No data available

# Terminal 1
Ctrl+C # (killing nc)

# Terminal 2
got data ''
got data ''
got data ''
got data ''
got data ''
got data ''
got data ''
got data ''
got data ''
got data ''
got data ''
got data ''
got data ''
got data ''
got data ''
got data ''
got data ''
got data ''
got data ''

推荐答案

recv 在发生错误时抛出异常.对等方关闭套接字不是错误,而是正常行为.事实上,它甚至不是完全关闭:对等方只是表明它不会再发送任何数据,但它可能仍会接收数据.TCP 连接只有在双方都表示不再发送任何数据时才会关闭,即双方都发送了 FIN.

recv throws an exception if an error occurred. Closing a socket by the peer is no error, but is a normal behavior. In fact it is not even a full close: the peer only indicates that it will not send any more data, but it might still receive data. The TCP connection is only closed if both sides indicate that they will not send any more data, i.e. each side has send the FIN.

这篇关于`sock.recv()` 当连接在非阻塞套接字上死机时返回空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 07:38