Python套接字sendall随机失败

时间:2014-04-29 16:52:44

标签: tcp jpeg transfer

我有一个简单的脚本,可以将图像文件从一台机器传输到另一台机器, 进行图像处理并将结果作为“骰子计数”返回。 问题是随机接收的图像是部分灰色的。似乎没有 关于转移何时不完整的原因,我认为代码中没有其他问题。 客户端没有给出错误或任何表示sendall失败或不完整的指示。 谢谢你们。

enter image description here

服务器代码:

def reciveImage():
    #create local buffer file 
    fo = open("C:/foo.jpg", "wb")
    print "inside reciveImage"
    while True:
        print "inside loop"
        data = client.recv(4096)
        print "data length: ", len(data)
        fo.write(data)
        print "data written"
        if (len(data) < 4096):
            break
            print "break"       
    fo.close()
    print "Image received"

和(简化的)客户端代码:

data = open("/home/nao/recordings/cameras/image1.jpg", "rb")    
        # prepare to send data
        binary_data = data.read()
        data.close()

        sock.sendall(binary_data)

正常服务器输出:

Client Command: findBlob. Requesting image...
inside reciveImage
inside loop
data length:  4096
data written
#... This happens a bunch of times....
inside loop
data length:  4096
data written
inside loop
data length:  1861
data written
Image received
dice count:  0
Waiting for a connection

但随机它只会循环几次或更少,如:

Client Command: findBlob. Requesting image...
inside reciveImage
inside loop
data length:  1448
data written
Image received
dice count:  0
Waiting for a connection

1 个答案:

答案 0 :(得分:1)

recv在收到所有数据之前不会阻塞,它只会阻塞,直到收到一些数据并返回它们。例如。如果客户端先发送512个字节然后再发送另一个512字节,那么即使你要求4096,你的recv也会返回前512个字节。所以你应该只在recv返回时断开,不再有数据可用(连接关闭)