Asyncio 和 pyzmq - 'utf-8' 编解码器无法解码位置 0 的字节 0xff [英] Asyncio and pyzmq - 'utf-8' codec can't decode byte 0xff in position 0
问题描述
我有一个 asyncio 服务器
,这是
你可以看到你得到的字节实际上对应于问候消息签名.
<小时>为了从 asyncio 中的 ZMQ 套接字接收消息,请使用像 aiozmq 之类的专用项目:
导入 aiozmq导入异步异步定义主(端口 = 5555):bind = "tcp://*:%s" % 端口rep = await aiozmq.create_zmq_stream(aiozmq.zmq.REP, bind=bind)消息,= 等待 rep.read()打印(消息.解码())rep.write([消息])如果 __name__ == '__main__':loop = asyncio.get_event_loop()loop.run_until_complete(main())循环关闭()
I have a asyncio server
, which is an example from the TCP Doc. However I'm connecting to it using pyzmq
and when the reader on the server tries to read I get a decode error. Any hint is highly appreciated. I've already tried encoding to utf-8 first, didn't help.
Server: (Python 3.6)
import asyncio
async def handle_echo(reader, writer):
data = await reader.read(100)
print(data)
message = data.decode()
loop = asyncio.get_event_loop()
coro = asyncio.start_server(handle_echo, '127.0.0.1', 5555, loop=loop)
server = loop.run_until_complete(coro)
loop.run_forever()
Client: (Python 2.7)
import zmq
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect ("tcp://localhost:%s" % 5555)
socket.send("test")
Full Trace:
future: <Task finished coro=<handle_echo() done, defined at "E:\Projects\AsyncIOserver.py:3> exception=UnicodeDecodeError('utf-8', b'\xff\x00\x00\x00\x00\x00\x00\x00\x01\x7f', 0, 1, 'invalid start byte')>
Traceback (most recent call last):
File "E:\Projects\AsyncIOserver.py", line 6, in handle_echo
message = data.decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
Zeromq uses the ZMTP protocol. It is a binary protocol so you won't be able to decode it directly.
If you're curious about it, check the ZMTP frames using wireshark and the ZMTP plugin:
You can see that the bytes you got actually corresponds to the greeting message signature.
In order to receive the messages from a ZMQ socket in asyncio, use a dedicated project like aiozmq:
import aiozmq
import asyncio
async def main(port=5555):
bind = "tcp://*:%s" % port
rep = await aiozmq.create_zmq_stream(aiozmq.zmq.REP, bind=bind)
message, = await rep.read()
print(message.decode())
rep.write([message])
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
这篇关于Asyncio 和 pyzmq - 'utf-8' 编解码器无法解码位置 0 的字节 0xff的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!