微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

来自 zeromq 的简单异步示例与 python

如何解决来自 zeromq 的简单异步示例与 python

我想用 Python 编写一个运行异步的简单 Pub/Sub。

我的想法是发布者发送一个 msg 并且订阅者正在异步收听它,而正常的同步 Python 代码仍在执行。

这是我的订阅代码

import asyncio
import zmq
from zmq.asyncio import Context

ctx = Context.instance()

async def recv():
    s = ctx.socket(zmq.SUB)
    s.connect('tcp://127.0.0.1:5001')
    s.subscribe(b'')
    await asyncio.sleep(1)
    #while True:
    msg = await s.recv_multipart()
    print('received',msg)
    s.close()

print("Test1")
asyncio.run(recv())
print("Test2")

这里是我的发布商代码

import zmq
import time 
import zmq.asyncio
import asyncio

ctx = zmq.asyncio.Context()


host = "127.0.0.1"
port = "5001"

# Creates a socket instance
async def publish():
    socket = ctx.socket(zmq.PUB)

    # Binds the socket to a predefined port on localhost
    socket.bind("tcp://{}:{}".format(host,port))

    await asyncio.sleep(1)

    # Sends a string message
    await socket.send_string("test")

asyncio.run(publish())

我希望我的订阅者的行是这样执行的:

Test1
Test2
test <= Msg comming back from publisher since I use async other python code should be executed first

但是会发生这样的情况:

Test1
test
Test2

这意味着它通常是同步执行的。

谁能解释一下我做错了什么?

非常感谢

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。