0

我想在 Python 中实现套接字客户端。服务器期望前 8 个字节包含以字节为单位的总传输大小。在 C 客户端中,我这样做了:

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 个字节并循环复制

4

1 回答 1

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"))

也可以看看:

于 2014-10-29T18:19:44.533 回答