请教如何使用python的socket发送二进制数据

Python016

请教如何使用python的socket发送二进制数据,第1张

socket发送的本来就是按二进制发送,你是想把数据打包成str用socket发出去吧?

可以用struct来打包

import struct

data = struct.pack('i', 123)

然后用socket发送就行了,这里打包一个整数的例子,struct很强大可以百度一下具体用法。

参考python 的struct module — Interpret strings as packed binary data, 用来将数据封装到类似C语言的结构体中进行发送。具体可以参考:

https://docs.python.org/2/library/struct.html

http://www.cnblogs.com/gala/archive/2011/09/22/2184801.html

http://stackoverflow.com/questions/3753589/packing-and-unpacking-variable-length-array-string-using-the-struct-module-in-py