字符串的python大小在套接字连接中高估了37个字节

时间:2015-11-17 09:29:23

标签: python sockets stream

我试图通过套接字连接向服务器发送 numpy.array 。我发现了一种似乎无法理解的行为:我使用 pickle.dumps 来获取我的数组对象的字符串表示并使用 sys.getsizeof 估计需要传输的字节数。但是,无论输入的大小如何,我的代码似乎都高估了37个字节的数据字符串长度。

服务器代码:

def recvall(sock, count):
    buf = b''
    while count:
        newbuf = sock.recv(count)
        if not newbuf: return None
        buf += newbuf
        count -= len(newbuf)

        print 'left to read: %i' %count

    return buf


if __name__ == '__main__':
    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    serversocket.bind((socket.gethostname(), 8089))  #visible to the outside world?
    serversocket.listen(5) # become a server socket, maximum 5 connections


    while True:
        connection, address = serversocket.accept()

        #read message size
        buf = recvall(connection, 4)
        bytes_to_read, = struct.unpack('!I', buf)

        print 'Message size: %i' % bytes_to_read

        #read message
        buf = recvall(connection, bytes_to_read - 37) #HACK: no idea why is that: size is overestimated by 37?!
        connection.close()

        reconstructed = pickle.loads(buf);

        img.imsave('out.png', reconstructed);
        print reconstructed.shape

客户代码:

#read image
im = img.imread(sys.argv[1])
im_str = pickle.dumps(im)


#### communication
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('ororea', 8089))

tmp = struct.pack('!I', int(sys.getsizeof(im_str))); #unsigned int

#print sys.getsizeof(tmp)

clientsocket.sendall(tmp)
clientsocket.sendall(im_str);

clientsocket.close()

像这样,转移有效,但我不明白为什么要发送少37个字节。

最好的问候, 星

1 个答案:

答案 0 :(得分:0)

@falsetru的评论有解决方案:

  

您应该使用len,而不是sys.getsizeof