6

I am writing a simple TCP server in python, and am trying to input a timeout. My current code:

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()

Issue is when I try to connect I get an error at data = conn.recv(1024)

error: [Errno 10035] A non-blocking socket operation could not be completed immediately

Code works without the timeout.

4

3 回答 3

3

您可以打开阻止:

    # ...
    conn.setblocking(1)
    return conn
# ...
于 2013-10-24T19:02:27.407 回答
2

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

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()
于 2015-12-02T03:32:03.317 回答
1

30 分钟前遇到了同样的问题。找到了一个简单的非优雅解决方法...如果您通过执行 time.sleep(1) 让套接字有时间呼吸,捕获 10035 错误并重试它就可以了。我正在使用 2.7.5 ...也许这是一个已修复的错误。不太确定。

代码示例......请理解这是我使用的非常简单的测试代码(一次只接收 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
于 2015-04-27T16:08:47.480 回答