[英]Sending text and binary using sockets in python
嗨,我想通過套接字XML發送像這樣。
<root>
<image ID='2'>
<![CDATA[ binary data with image ]]>
</image>
</root>
我有問題,因為圖像是二進制數據,其他部分是字符串。 我正在發送多張圖片,我需要有ID。
主要問題是如何處理二進制數據和字符串數據。 我試圖將圖像轉換為str,但是我無法還原。
在xml
嵌入二進制文件的一種有用方法是對其進行base64編碼。 例如,這是XAML
用於發送小圖像的方法。 您可以在代碼中的某處這樣做:
import base64
img = open('some.png',rb').read()
base64.b64encode(img)
# append it to your buffer
在另一邊:
#get the img portion in the buffer
import base64
img = base64.b64decode(fetched_img)
# write it to disk or whatever
這是在XML
處理二進制文件的標准/常用方法。
使用base64
非常簡單,這是解釋器中的一個示例:
In [1]: import base64
In [4]: base64.b64encode('example')
Out[4]: 'ZXhhbXBsZQ=='
In [5]: base64.b64decode('ZXhhbXBsZQ==')
Out[5]: 'example'
希望這可以幫助!
只需將套接字作為二進制連接-無論如何,您可能根本不關心換行轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.