向python服务器添加超时时出现非阻塞错误

时间:2013-10-24 15:49:50

标签: python sockets tcpserver

我在python中编写一个简单的TCP服务器,我正在尝试输入超时。我目前的代码:

import socket


def connect():
    HOST = ''                 # Symbolic name meaning the local host
    PORT = 5007             # Arbitrary non-privileged port
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((HOST, PORT))
    s.listen(1)
    s.settimeout(5)
    conn, addr = s.accept()
    print 'Connected by', addr
    return conn

conn = connect()

while 1:
    data = conn.recv(1024)
    if not data: break
    print data
conn.close()

问题是当我尝试连接时,我在data = conn.recv(1024)

时收到错误
error: [Errno 10035] A non-blocking socket operation could not be completed immediately

代码在没有超时的情况下工作。

3 个答案:

答案 0 :(得分:3)

您可以启用屏蔽功能:

    # ...
    conn.setblocking(1)
    return conn
# ...

答案 1 :(得分:1)

30分钟前遇到同样的问题。找到一个简单的非优雅的工作...如果你通过time.sleep(1)给插座时间呼吸,捕捉10035错误并重试它是有效的。我正在使用2.7.5 ......也许这是一个修复过的bug。不太确定。

代码示例...请理解这是我使用的非常简单的测试代码(一次仅收集1个字节)。所以's'是具有10秒超时的套接字,'numbytes'是我需要的字节数...

def getbytes(s,numbytes):
     din = ''
     socketerror10035count = 0
     while True:
          try:
               r = s.recv(1).encode('hex')
               din += r
               if len(din)/2 == numbytes:
                    print 'returning',len(din)/2, 'bytes'
                    break
          except socket.timeout as e:
               din = 'socket timeout'
               break
          except socket.error as e:
               if e[0] == 10035 and socketerror10035count < 5:
                    socketerror10035count = socketerror10035count  +1
                    time.sleep(1)
               else:
                    din = 'socket error'
                    break
          except:
               din = 'deaddead'
               break
     return din

答案 2 :(得分:1)

尝试设置套接字上的超时和连接上的阻塞。像这样:

import socket 

def connect():
    HOST = ''                 # Symbolic name meaning the local host
    PORT = 5007             # Arbitrary non-privileged port
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(5)
    s.bind((HOST, PORT))
    s.listen(1)  
    return s

s = connect()

while 1:
    conn, addr = s.accept()
    print 'Connected by', addr
    conn.setblocking(1)
    data = conn.recv(1024)
    conn.close()
    if not data: break
    print data
s.close()