套接字等待连接超时

时间:2015-11-05 16:34:00

标签: python sockets timeout

我正在尝试实现一个超时,当超过定义的时间间隔没有连接时,终止python脚本。到目前为止,我设法使用以下代码实现超时:

import sys
import socket

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the port
server_address = ('192.168.43.112', 5001)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)

# Listen for incoming connections
sock.listen(1)

while True:
    try:
        # Wait for a connection
        print >>sys.stderr, 'waiting for a connection'
        connection, client_address = sock.accept()

        try:
            print >>sys.stderr, 'connection from', client_address

            # Receive the data in small chunks and retransmit it
            while True:
                data = connection.recv(16)
                print >>sys.stderr, 'received "%s"' % data
                if data:
                    print >>sys.stderr, 'Do stuff here'
                else:
                    print >>sys.stderr, 'no more data from', client_address
                    sock.settimeout(5)
                    break

        finally:
            # Clean up the connection
            connection.close()

    except socket.timeout:
        break

在建立连接并结束相同连接之后,代码正常工作,5秒后脚本终止。但是,如果在超时窗口期间我尝试进行另一个连接,则会出现以下错误:

starting up on 192.168.43.112 port 5001
waiting for a connection
connection from ('192.168.43.1', 47550)
received "Data 0
"
Do stuff here
received ""
no more data from ('192.168.43.1', 47550)
waiting for a connection
connection from ('192.168.43.1', 39010)
---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
/Users/location/Desktop/sandbox/data_fetcher.py in <module>()
     24             # Receive the data in small chunks and retransmit it
     25             while True:
---> 26                 data = connection.recv(16)
     27                 print >>sys.stderr, 'received "%s"' % data
     28                 if data:

error: [Errno 35] Resource temporarily unavailable

1 个答案:

答案 0 :(得分:1)

我不完全确定你希望这一切都能如何发挥作用,我觉得它现在以这种方式发生有点令人惊讶(我没想到超时会产生这种效果),但是基于EAGAIN错误(错误35),发生的事情是主套接字上的超时 - 只有在您第一次连接后才设置 - 导致第二个 -accepted socket也处于非阻塞模式。这意味着当您致电connection.recv并且没有立即数据时,您就会获得OSError

我怀疑其中一些可能会在操作系统之间有所不同,但我能够在FreeBSD上重现这一点(你可能在Linux上运行)。

围绕它的最小变化 - 我认为这不一定是编写代码的最佳方式,但它确实有效 - 明确将接受的套接字设置为阻塞:

        # Wait for a connection
        print >>sys.stderr, 'waiting for a connection'
        connection, client_address = sock.accept()

        connection.setblocking(1)

有了这个,代码表现得更好(我添加了一个小的测试框架,它将代码作为一个单独的进程旋转,然后使用不同的延迟创建多个连接)。