即使应该传递 if 语句,协议也会将数据写入文件

Protocol writes data into file even when the if statement should be passed

我想做一个协议,通过将给定数据写入客户端 C:\ 目录中的文件,有效地将 jpg 文件数据从服务器写入客户端。

当新的 jpg 文件在客户端计算机上存在并完成时,协议会执行此操作,

但是协议一直在重复自己,将数据写入文件而没有结束,

导致它具有巨大的文件大小

并且协议没有结束,所以我的客户端可以访问我拥有的其他协议。

谁能注意到我做错了什么?

服务器协议:

if data == "screen shot":
    im = ImageGrab.grab()
    im.save(r'C:\screen.jpg')
    file = open(r'C:\screen.jpg','rb').read()

    sizeoffile = os.stat(r'C:\screen.jpg').st_size
    client_socket.send(str(sizeoffile))
    if data == "Send file":
        client_socket.send(file)

客户端协议:

if x == "screen shot":
    print "Here you go"
    sizeof = my_socket.recv(1024)
    print "Size of file: " + str(sizeof)
    accumulated = bytes(0)
    doit = True
    file = open(r'C:\serverscreen.jpg','wb')
    my_socket.send("Send file")

    while doit:
        if accumulated < sizeof:
            print "Receiving..."
            my_socket.send("GOT IT")
            data = my_socket.recv(1024)
            accumulated = os.stat(r'C:\serverscreen.jpg').st_size # do a loop to check if accumulated equals sizeof to know if entire file has been, accumulated
            print "Accumulated: " + str(accumulated)
            file.write(data)
        else:
            doit = False

    file.close()

更新

客户端协议:

if x == "screen shot":
    print "Here you go"
    sizeof = int(my_socket.recv(1024))
    print "Size of file: " + str(sizeof)
    accumulated = bytes(0)
    doit = True
    file = open(r'C:\serverscreen.jpg','wb')
    my_socket.send("Send file")
    while doit:
        if accumulated < sizeof:
            print "Receiving..."
            my_socket.send("GOT IT")
            data = my_socket.recv(1024)#round(float(sizeof))))
            accumulated += struct.unpack('l',data) #os.stat(r'C:\serverscreen.jpg').st_size # do a loop to check if accumulated equels sizeof to know if entire file has been, accumulaed
            print "Accumulated: " + str(accumulated)
            file.write(data)
        else:
            doit = False

    file.close()

好的,我们来解决这里的问题。

  1. sizeof = int(my_socket.recv(1024)):你不知道这个数字正好是1024位长。事实上,它可能比那短得多,所以这吸收了部分图像数据。需要在服务器端打包成struct.pack()等宽的字节字段,然后在客户端解包成相同格式
  2. accumulated = bytes(0):在Python 2.7中,bytesstr完全同义(在3.x中它仍然是一个类似字符串的东西,但略不同的)。换句话说,这不是一个整数,它是一个字符串。如果您一直在使用 Python 3,这会在 if accumulated < sizeof: 行引发异常,因为 3.x 不允许将整数与字符串进行比较。
  3. my_socket.send("Send file")/my_socket.send("GOT IT"):由于服务器从不调用 recv(),因此该数据理论上可以填满 TCP 缓冲区并阻塞。实际上它不会,因为你只发送了少量,但一般来说,除非对方收到它们,否则你不能发送东西。
  4. accumulated += struct.unpack('l',data):那不行。你实际上想要 len(data) 这里。