【问题标题】:Data lost on receiver side in python socket programmingpython socket编程中接收方的数据丢失
【发布时间】:2012-05-15 16:36:26
【问题描述】:

我在 python 套接字编程中制作了一个简单的服务器-客户端代码。客户端获取其侧的屏幕截图(图像)并将其发送到服务器。当我使用'localhost'传输图像时它工作正常,即从一个文件夹到另一个......但主要问题是当图像传输到另一台计算机时......服务器端接收到的图像已损坏......进一步更多我观察到客户端(发送方图像,即未损坏的图像)和服务器(接收方图像,即损坏的图像)之间的差异每次几乎是 1Kb............

我的客户端(发送方)代码是--

os.system('scrot screen.bmp') #command to take screen shot


FILE = "screen.bmp"
f = open(FILE, "rb")
data = f.read()
f.close()
del f

imagesize = int(os.path.getsize('screen.bmp'))

sendsize =  '%1024s' %imagesize
s.sendall(str(sendsize))
print 'length of data = ',len(data)
s.sendall(str(len(data)))
s.sendall(str(data))

和服务器端(接收端)---

filename='screen.bmp'
print '[Media] Starting media transfer for ',filename   
os.system('rm -f screen.bmp')
f = open(filename,"wb")
expsizeimage = int(conn.recv(1024))
data1 = conn.recv(1024)

data2=''
for i in range(0,len(data1)):
    if(not(data1[i]=='0' or data1[i]=='1' or data1[i]=='2' or data1[i]=='3' or data1[i]=='4' or data1[i]=='5' or data1[i]=='6' or data1[i]=='7' or data1[i]=='8' or data1[i]=='9')):
        break
    data2=data2+data1[i]
print '------------'+data2+'-------------'+str(m)+'----------------'
print 'size of data:' ,int(data2)
print 'the expected size of image is: ', expsizeimage
data=9
del data
sized=0;
while 1:

    data = conn.recv(expsizeimage)
    print 'received length of image = ',len(data)               
    f.write(data)

    sized=sized+len(data)
    print "sized------"+str(sized)
    del data
    if(sized>=int(data2)):

        break

print "saved the screentshot data recieved"

【问题讨论】:

  • 如果您已收到除 1024 字节之外的所有数据,则您明确breaking。你预计会发生什么?
  • 当没有数据时你应该可以安全地破解,例如if not data: break。你不需要做任何花哨的事情来摆脱。

标签: python image sockets tcp


【解决方案1】:

这两个程序未经测试,是为最新版本的 Python 编写的,并且出于安全目的切换您的客户端/服务器关系。


Source.py

import os, struct, socket

def main():
    # Take screenshot and load the data.
    os.system('scrot image.bmp')
    with open('image.bmp', 'rb') as file:
        data = file.read()
    # Construct message with data size.
    size = struct.pack('!I', len(data))
    message = size + data
    # Open up a server socket.
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(('', 65000))
    server.listen(5)
    # Constantly server incoming clients.
    while True:
        client, address = server.accept()
        print('Sending data to:', address)
        # Send the data and shutdown properly.
        client.sendall(message)
        client.shutdown(socket.SHUT_RDWR)
        client.close()

if __name__ == '__main__':
    main()

Destination.py

import socket, struct

def main(host):
    # Connect to server and get image size.
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect((host, 65000))
    packed = recvall(client, struct.calcsize('!I'))
    # Decode the size and get the image data.
    size = struct.unpack('!I', packed)[0]
    print('Receiving data from:', host)
    data = recvall(client, size)
    # Shutdown the socket and create the image file.
    client.shutdown(socket.SHUT_RDWR)
    client.close()
    with open('image.bmp', 'wb') as file:
        file.write(data)

def recvall(sock, size):
    message = bytearray()
    # Loop until all expected data is received.
    while len(message) < size:
        buffer = sock.recv(size - len(message))
        if not buffer:
            # End of stream was found when unexpected.
            raise EOFError('Could not receive all expected data!')
        message.extend(buffer)
    return bytes(message)

if __name__ == '__main__':
    main('localhost')

【讨论】:

  • 它给出了一个错误 Traceback(最近一次调用最后):文件“stackc.py”,第 30 行,在 main('localhost') 文件“stackc.py”,第 6 行,在主client.connect((host,50001))文件“/usr/lib/python2.7/socket.py”,第224行,在meth返回getattr(self._sock,name)(*args)socket.error: [Errno 111] 连接被拒绝
  • 在运行客户端(Destination.py)之前需要运行服务端(Source.py)。此外,您可能需要考虑它在此程序中使用的 bytes 类型,并改用 str(取决于您使用的 Python 版本)。
  • 仍然遇到同样的问题
  • 好的,现在应该修好了。请注意以下更改:Source.py 中的 server.bind(('', 65000)) 和 Destination.py 中的 size = struct.unpack('!I', packed)[0]。很抱歉造成混乱!
  • 如果您喜欢这个答案,您可以考虑投票。如果答案有助于解决您的问题,您也可以选择接受它作为首选答案(复选标记)。
猜你喜欢
  • 2018-07-15
  • 2013-07-14
  • 2023-03-11
  • 2020-03-17
  • 2015-07-22
  • 1970-01-01
  • 2012-07-15
相关资源
最近更新 更多