在Python中实现二进制协议(扭曲)
我在 node.js 中编写了一个实现二进制协议的 TCP 服务器。 在 Node.js 中使用缓冲区这非常容易。 http://nodejs.org/docs/v0.5.3/api/buffers.html
我正在寻找一种类似的方法来使用twisted 在 python 2.7 中实现我的协议。 但是,如果有更好的工具可以将 python 3 和某种事件 I/O 结合起来,请告诉我。由于 python 3 中的 bytes 对象,乍一看我觉得 python 3 更擅长处理二进制协议。我需要处理许多 TCP(和 UDP)连接并编写一些 GUI。
以下是如何在 node.js 中实现我的协议:
var buf = new Buffer(5+data.length), //headers + data (data is also a buffer)
action = 0x01;
buf[0] = action;
buf.writeUInt16(data.length,1,'big'); //write content length in at offset 1
buf.writeUint16(12345,5,'big'); //message identifier at offset 3
data.copy(buf,5); //copy data into message at offset 5
socket.write(buf);
我希望获得有关如何在 python 中实现类似指令的示例。
编辑:这就是我如何使用 python struct 模块实现我的协议:
self.transport.write(struct.pack('!bHH',action,data.length, sock_id) + data)
I've written a TCP server in node.js implementing a binary protocol.
Using buffers this was very easy in node.js.
http://nodejs.org/docs/v0.5.3/api/buffers.html
I'm looking for a similar way to implement my protocol in python 2.7 using twisted.
However, if there's a better tool for the job combining python 3 and some sort of evented I/O, please let me know. Because of bytes object in python 3, at first look it seams to me that python 3 is better at handling binary protocols. I need to handle many TCP(and UDP) connections and write a bit of GUI.
Here's how implement my protocol in node.js:
var buf = new Buffer(5+data.length), //headers + data (data is also a buffer)
action = 0x01;
buf[0] = action;
buf.writeUInt16(data.length,1,'big'); //write content length in at offset 1
buf.writeUint16(12345,5,'big'); //message identifier at offset 3
data.copy(buf,5); //copy data into message at offset 5
socket.write(buf);
I would appreciate examples for how to achieve similar instructions in python.
Edit: this is how I was able to implement my protocol using the python struct module:
self.transport.write(struct.pack('!bHH',action,data.length, sock_id) + data)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
听起来标准的 Python
struct
模块会做你想做的事情需要。它允许您准确指定二进制数据的布局。Python 2 和 Python 3 中处理二进制协议的功能是等效的。
It sounds like the standard Python
struct
module will do what you need. It allows you to specify exactly what the layout of binary data needs to be.The capabilities of handling binary protocols in Python 2 and Python 3 are equivalent.
如果关注效率并且您想要执行诸如异或整个字节块之类的操作,您可能需要查看 Python bytearray,它是一个可变的字节数组。
If efficiency is of concern and you want to do stuff like i.e. XOR a whole chunk of bytes, you migh want to look at Python bytearray, which is a mutable array of bytes.
如果您想对
struct
模块进行更多抽象,请尝试protlib
。好处是你可以处理开箱即用的 python 对象而不是单个字段。
If you want to have a bit more abstraction over the
struct
module, tryprotlib
. The nice thing is that you can deal with python objects out of the box instead of single fields.