# Socket to talk to server print "Connecting to hello world server..." socket = context.socket(zmq.REQ) socket.connect ("tcp://localhost:5555") # Do 10 requests, waiting each time for a response for req_no in range (10): socket.send ("Hello") # Get the reply. message = socket.recv() print "Received reply ", req_no, "[", message, "]"
context = zmq.Context() sender = context.socket(zmq.PUSH) sender.bind("tcp://*:5557") print "Press Enter when the workers are ready: " _ = raw_input() print "Sending tasks to workers..." base_url = 'http://xkcd.com/' urls = [base_url + str(i) for i in xrange(1, int(sys.argv[1]))] for url in urls: sender.send(url)
import requests from lxml import etree def get_title(url): """Given a XKCD url, retrieve the title of the image.""" r = requests.get(url) tree = etree.HTML(r.content) title = tree.xpath('//div[@id="comic"]/img/@title') if title: return title[0] else: return None
to receive messages on receiver = context.socket(zmq.PULL) receiver.connect("tcp://localhost:5557") # Socket to send messages to sender = context.socket(zmq.PUSH) sender.connect("tcp://localhost:5558") # Process tasks forever while True: s = receiver.recv() title = get_title(s) print s, title # Send a JSON payload to sink sender.send(json.dumps({"url":s, "title":title}))