Python SocketServer cannot receive all data
I am trying to implement a SocketServer to receive a file from a mobile app:
- The mobile app sends the file size.
- The mobile app is sending the file.
File size received correctly. In the app, all data is sent. However, SocketServer cannot receive all data and sticks.
import SocketServer
import struct
class MyTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
size = self.readLong()
print 'Payload size', size
bytes = self.readExact(size)
print 'Read bytes'
self.request.sendall('Hurray!')
def readLong(self):
return long(struct.unpack('>q', self.readExact(8))[0])
def readExact(self, num):
buf = bytearray()
remaining = num
while remaining > 0:
chunk = self.request.recv(remaining)
if not chunk:
raise EOFError('Could not receive all expected data!')
buf.extend(chunk)
remaining -= len(chunk)
return buf
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
solvable As @ 6502 suggested, the problem was in a mobile app where I used buffered output but never blushed.
source to share
The code seems to be correct.
Does your call return recv
an empty string? If this happens, an error will occur.
Also are you waiting on the mobile side for ack? If you don't and just leave the mobile side, maybe the implementation there closes the endpoint too early without sending all the data.
Another possibility is that the sender is incorrectly handling the fact that it send
may also return a value smaller than the specified size (this happens when the send buffers are full).
source to share