ZeroMQ REQ/REP memo

ZeroMQ request/reply memo.
install:

sudo port install py-zmq

py:

import sys
import zmq
from zmq.eventloop import ioloop

def rep_handler(sock, events):
    msg = sock.recv()
    sock.send(msg)

def rep():
    print "*** rep"
    loop = ioloop.IOLoop.instance()
    ctx = zmq.Context()
    sock = ctx.socket(zmq.REP)
    sock.bind('tcp://127.0.0.1:5555')
    loop.add_handler(sock, rep_handler, zmq.POLLIN)
    loop.start()

def req():
    print "*** req"
    ctx = zmq.Context()
    sock = ctx.socket(zmq.REQ)
    sock.connect('tcp://127.0.0.1:5555')
    sock.send('hello')
    print sock.recv()

def main():
    command = sys.argv[1].lower()
    if command == "req":
        req()
    elif command == "rep":
        rep()

main()

Leave a Reply

Your email address will not be published. Required fields are marked *