我正在使用 python SocketServer 下载/上传多图像文件。
服务器代码
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
'''
Here is other codes......
'''
#start sending files to client...
for img_name, img_size in dict_image_sizes.iteritems():
image_file = open(u"%s\\%s" % (image_folder, img_name), 'rb')
while True:
image_chunk = image_file.read(32768)
if not image_chunk:
break
self.request.sendall(image_chunk)
image_file.close()
客户代码:
#start recving...
for img_name, img_size in dict_image_sizes.iteritems():
each_image_file = open(u'%s\\%s\\%s' % (env.cache_path, relative_path, img_name), 'wb')
chunk_size = 4096
img_size_int = int(int(img_size)/chunk_size)
img_size_mod = int(math.fmod(int(img_size), chunk_size))
import time
image_chunk = ''
for i in range(img_size_int):
image_chunk += sock.recv(chunk_size)
#time.sleep(0.001)
image_chunk += sock.recv(img_size_mod)
each_image_file.write(image_chunk)
each_image_file.close()
问题是,如果我取消标记
#time.sleep(0.001)
在客户端代码中,它会好的。否则,许多图像可能会损坏(并非总是如此,有时)。
Corrupt JPEG data: premature end of data segment
有没有办法解决这个问题?我试图添加
sock.settimeout(1)
对于客户,但它不起作用。
问题解决了。我们需要检查发送/接收每次返回的确切字节。在这里咨询:Python中的非阻塞套接字?
def recvall(sock, size):
data = ''
while len(data) < size:
d = sock.recv(size - len(data))
if not d:
# Connection closed by remote host, do what best for you
return None
data += d
return data
def sendall(sock, data):
while data:
sent = sock.send(data)
data = data[sent:]