2014-10-29 150 views
0

我想在Python中實現套接字客戶端。服務器期望前8個字節包含以字節爲單位的總傳輸大小。在C客戶端,我這樣做:在Python中使用變量值作爲字節數組

uint64_t total_size = zsize + sizeof (uint64_t); 
uint8_t* xmlrpc_call = malloc (total_size); 
memcpy (xmlrpc_call, &total_size, sizeof (uint64_t)); 
memcpy (xmlrpc_call + sizeof (uint64_t), zbuf, zsize); 

其中zsize和zbuff是我想傳輸的大小和數據。 在Python中,我創建的字節數組是這樣的:

cmd="<xml>do_reboot</xml>" 
result = deflate (bytes(cmd,"iso-8859-1")) 
size = len(result)+8 

什麼是最好的,以填補頭在Python?如果沒有分離值8個字節,它在循環複製

+0

你正在執行正常的XML-RPC嗎?你有什麼理由不能使用'xmlrpclib'嗎? – 2014-10-29 11:42:00

+0

這是自定義XMLRPC,加密和zlibbed。我應該支持它的協議,原因是 – pugnator 2014-10-29 12:09:52

回答

1

你可以使用struct模塊,將包格式的數據轉換成二進制數據,你想

import struct 
# ...your code for deflating and processing data here... 

result_size = len(result) 
# `@` means use native size, `I` means unsigned int, `s` means char[]. 
# the encoding for `bytes()` should be changed to whatever you need 
to_send = struct.pack("@I{0}s".format(result_size), result_size, bytes(result, "utf-8")) 

參見:

+0

奇怪,但頭部始終爲0 – pugnator 2014-10-29 18:41:22

+0

頭部在那裏,您可能正在查看填充,當'結果'=''美好的一天'','to_send' = 'b'\ x08 \ x00 \ x00 \ x00good day''。您也可以使用'to_send [0]'來檢查。如果你想在數字前填充,你可以用'>'代替'@' – XrXrXr 2014-10-29 21:31:59

+0

謝謝!這正是我需要的 – pugnator 2014-10-29 21:52:34