![](/img/trans.png)
[英]twisted not sending entire file with twisted client and server tcp transfer
[英]twisted image transfer from client to server gives bad format error
我試圖使用TCP從服務器向客戶端發送圖像文件。 我嘗試打開文件,讀取文件,然后使用self.transport.write進行傳輸。 在客戶端,當我接收數據時,我以追加模式打開一個名為Image的文件,並對其進行寫入。
客戶:
class EchoClient(protocol.Protocol):
def dataReceived(self, data):
print 'writing to file'
f = open('image.png','a')
f.write(data)
f.close()
服務器(繼承協議):
//somewhere in the code
image = open(self.newdict[device_str] + attribute_str + '.png')
data = image.read()
image.close()
self.comm_protocol.transport.write(data)
在客戶端打開文件會出現錯誤的格式錯誤。 有什么想法我做錯了嗎? 將圖像作為字符串流式傳輸的想法不好嗎? 如果是這樣,還有其他方法可以將數據傳輸到客戶端嗎?
您必須以二進制模式打開文件,並帶有'b'標志,例如open(..., 'wb'
)。
文件損壞的原因是“文本模式”執行以下兩項操作之一:
\\n
替換為\\r\\n
。 現在,如果它是一個文本文件,您幾乎無法分辨出區別。 但是,如果它是二進制文件,則該字節可能不再表示“換行符”。 通常,二進制文件是由固定長度的結構構成的,因此將兩個字節粘貼在預期的一個位置會造成各種破壞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.