具有aiozmq流的简单PUB / SUB

时间:2018-08-22 08:40:31

标签: python zeromq

我试图用aiozmq流制作一个简单的PUB / SUB(出于某些原因,我不想使用aiozmq rpc)没有成功:

pub.py

# coding: utf-8
import asyncio
import time

import aiozmq
import zmq


async def do():
    stream = await aiozmq.stream.create_zmq_stream(
        zmq_type=zmq.PUB,
        bind='tcp://127.0.0.1:5556',
    )
    while True:
        await asyncio.sleep(1)
        msg = [str(time.time()).encode()]
        print('write ', msg)
        stream.write(msg)

loop = asyncio.get_event_loop()
loop.run_until_complete(do())

sub.py

# coding: utf-8
import asyncio

import aiozmq
import zmq


async def do():
    stream = await aiozmq.stream.create_zmq_stream(
        zmq_type=zmq.SUB,
        connect='tcp://127.0.0.1:5556',
    )
    while True:
        print('wait ...')
        msg = await stream.read()
        print('received ', msg)

loop = asyncio.get_event_loop()
loop.run_until_complete(do())

执行pub.py时:

python pub.py      
write  [b'1534927086.914483']
write  [b'1534927087.9154818']
write  [b'1534927088.9164672']

然后执行sub.py:

python sub.py
wait ...

我想念什么?

1 个答案:

答案 0 :(得分:0)

仅错过sub.py中的传输订阅行。有一个有效的sub.py:

# coding: utf-8
import asyncio

import aiozmq
import zmq


async def do():
    stream = await aiozmq.stream.create_zmq_stream(
        zmq_type=zmq.SUB,
        connect='tcp://127.0.0.1:5556',
    )
    stream.transport.subscribe(b'')

    while True:
        print('wait ...')
        msg = await stream.read()
        print('received ', msg)

loop = asyncio.get_event_loop()
loop.run_until_complete(do())

生产者:

python sub.py 
wait ...
received  [b'1534927504.0462704']
wait ...
received  [b'1534927505.0478334']