Python Socket下载/上传图像文件丢失二进制文件

时间:2013-10-29 06:22:49

标签: python sockets socketserver

我正在使用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) 

对于客户来说,但它不起作用。

解决了问题。我们需要检查send / recv每次返回的确切字节数。 请咨询此处:Non-blocking socket in 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:]

1 个答案:

答案 0 :(得分:1)

套接字连接有最大OS发送/接收缓冲区大小。如果没有time.sleep,则会立即发送所有请求并填充缓冲区。