Python服务器:如何接收X秒的数据?

时间:2017-06-13 12:16:27

标签: python sockets server

为了测试porpoises,我的Python服务器必须接收X秒的数据。

def ReceiveUplinkData(connection, uplinkTimer):
    try:
        global uplinkDataBlockSize

        print 'Server is receiving uplink data for ' + str(uplinkTimer) + ' seconds'

        bytesRecieved = 0
        start_time = time.time()

        while True:
            data = connection.recv(uplinkDataBlockSize)
            #print 'Server received "%s"' % data
            if data:
                bytesRecieved += len(data)

            if time.time() - start_time >= uplinkTimer:
                break

    # +=+=+=+=+=+=+=+=+=+=+=+=+=
    except KeyboardInterrupt, e:  # Ctrl-C
        raise e
    except SystemExit, e:  # sys.exit()
        raise e
    except Exception, e:
        print 'Error, undetected exception'
        print str(e)
        traceback.print_exc()
        os._exit(1)

    # +=+=+=+=+=+=+=+=+=+=+=+=+=
    finally:
            end_time = time.time()
            print 'End of uplink data transfer. ' + str(bytesRecieved) + 
                  ' bytes received in ' + str(end_time - start_time) + ' seconds'

如果我阻止了连接,那么如果客户端发送的时间少于X秒,它就会挂起。

我将其设为非阻塞(connection.setblocking(0)),然后我遇到异常

Error, undetected exception
[Errno 10035] A non-blocking socket operation could not be completed immediately
Traceback (most recent call last):
  File "c:\server.py", line 28, in ReceiveUplinkData
    data = connection.recv(uplinkDataBlockSize)
error: [Errno 10035] A non-blocking socket operation could not be completed immediately

有人可以告诉我如何修复我的代码,或者指出我可以复制的简单示例吗?

1 个答案:

答案 0 :(得分:0)

更改while条件以跟踪已过去的时间

while time.time() - start_time >= uplinkTimer:
    data = connection.recv(uplinkDataBlockSize)
    #print 'Server received "%s"' % data
    if data:
        bytesRecieved += len(data)

您获得异常的原因可能是因为没有更多数据要接收。根据文档,当您将套接字设置为非阻塞模式时,如果recv()调用未找到任何数据,或者send()调用无法立即处理数据,则会出现错误异常被提出。