For testing porpoises, my Python server has to receive data for X seconds.
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'
If I make the connection blocking, then it hangs if the client transmits for less than X seconds.
I make it non-blocking ( connection.setblocking(0)
), then I hit an exception
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
Can someone either tell me how to fix my code, or point me at simple example which I can copy?
Change your while
condition to track how much time has elapsed
while time.time() - start_time >= uplinkTimer:
data = connection.recv(uplinkDataBlockSize)
#print 'Server received "%s"' % data
if data:
bytesRecieved += len(data)
The reason you are getting an exceptionad could be because there is no more data to receive. Per the docs, when you set the socket to non-blocking mode, if a recv()
call doesn't find any data, or if a send()
call can't immediately dispose of the data, an error exception is raised.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.