twisted image transfer from client to server gives bad format error

最后都变了- 提交于 2019-12-14 02:18:59

问题


I was trying to send an image file using tcp from server to client. I tried opening the file, reading it and then transporting it using self.transport.write. On the client side, when I receive data, I open a file named Image in append mode, and write to it.

client:

class EchoClient(protocol.Protocol):
    def dataReceived(self, data):         
        print 'writing to file'
        f = open('image.png','a')
        f.write(data)
        f.close() 

server (inherits Protocol):

//somewhere in the code

     image = open(self.newdict[device_str] + attribute_str + '.png')
     data = image.read()
     image.close()
     self.comm_protocol.transport.write(data)

Opening the file on client side gives bad format error. Any ideas what I am doing wrong ? Is the idea to stream the image as a string bad ? If so, is there some other way I can transfer data to the client ?


回答1:


You have to open the file in binary mode, with the 'b' flag, like open(..., 'wb').

The reason that the file gets corrupted is that "text mode" does one of two things:

  1. on UNIX, it does nothing.
  2. on Windows, it just replaces \n with \r\n.

Now, if it's a text file, you can hardly tell the difference. But, if it's a binary file, that byte might doesn't mean "newline" any more. Generally, binary files are constructed from fixed-length structures, so sticking two bytes in where one is expected will cause all kinds of havoc.



来源:https://stackoverflow.com/questions/16448925/twisted-image-transfer-from-client-to-server-gives-bad-format-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!