File: coroutines.py

package info (click to toggle)
pyzmq 20.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 2,228 kB
  • sloc: python: 14,051; ansic: 941; cpp: 315; makefile: 179; sh: 32
file content (52 lines) | stat: -rw-r--r-- 1,161 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""Example using zmq with asyncio coroutines"""
# Copyright (c) PyZMQ Developers.
# This example is in the public domain (CC-0)

import time

import zmq
from zmq.asyncio import Context, Poller
import asyncio

url = 'tcp://127.0.0.1:5555'

ctx = Context.instance()


async def ping():
    """print dots to indicate idleness"""
    while True:
        await asyncio.sleep(0.5)
        print('.')


async def receiver():
    """receive messages with polling"""
    pull = ctx.socket(zmq.PULL)
    pull.connect(url)
    poller = Poller()
    poller.register(pull, zmq.POLLIN)
    while True:
        events = await poller.poll()
        if pull in dict(events):
            print("recving", events)
            msg = await pull.recv_multipart()
            print('recvd', msg)


async def sender():
    """send a message every second"""
    tic = time.time()
    push = ctx.socket(zmq.PUSH)
    push.bind(url)
    while True:
        print("sending")
        await push.send_multipart([str(time.time() - tic).encode('ascii')])
        await asyncio.sleep(1)


asyncio.get_event_loop().run_until_complete(asyncio.wait([
    ping(),
    receiver(),
    sender(),
]))