Skip to content

Commit

Permalink
Add example for core level
Browse files Browse the repository at this point in the history
  • Loading branch information
asvetlov committed Nov 23, 2014
1 parent 61e9b75 commit ca5d112
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
7 changes: 7 additions & 0 deletions docs/examples.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ There is a list of examples from `aiozmq/examples <https://github.com/aio-libs/a

Every example is a correct tiny python program.

.. _aiozmq-examples-core-dealer-router:

Simple DEALER-ROUTER pair implemented on Core level
---------------------------------------------------

.. literalinclude:: ../examples/core_dealer_router.py

.. _aiozmq-examples-rpc-rpc:

Remote Procedure Call
Expand Down
74 changes: 74 additions & 0 deletions examples/core_dealer_router.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import asyncio
import aiozmq
import zmq


class ZmqDealerProtocol(aiozmq.ZmqProtocol):

transport = None

def __init__(self, queue, on_close):
self.queue = queue
self.on_close = on_close

def connection_made(self, transport):
self.transport = transport

def msg_received(self, msg):
self.queue.put_nowait(msg)

def connection_lost(self, exc):
self.on_close.set_result(exc)


class ZmqRouterProtocol(aiozmq.ZmqProtocol):

transport = None

def __init__(self, on_close):
self.on_close = on_close

def connection_made(self, transport):
self.transport = transport

def msg_received(self, msg):
self.transport.write(msg)

def connection_lost(self, exc):
self.on_close.set_result(exc)


@asyncio.coroutine
def go():
router_closed = asyncio.Future()
dealer_closed = asyncio.Future()
router, _ = yield from aiozmq.create_zmq_connection(
lambda: ZmqRouterProtocol(router_closed),
zmq.ROUTER,
bind='tcp://127.0.0.1:*')

addr = next(iter(router.bindings()))
queue = asyncio.Queue()
dealer, _ = yield from aiozmq.create_zmq_connection(
lambda: ZmqDealerProtocol(queue, dealer_closed),
zmq.DEALER,
connect=addr)

for i in range(10):
msg = (b'data', b'ask', str(i).encode('utf-8'))
dealer.write(msg)
answer = yield from queue.get()
print(answer)
dealer.close()
yield from dealer_closed
router.close()
yield from router_closed


def main():
asyncio.get_event_loop().run_until_complete(go())
print("DONE")


if __name__ == '__main__':
main()

0 comments on commit ca5d112

Please sign in to comment.