Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@minrk
Forked from amacleod/zmq_cli.py
Created January 17, 2011 08:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minrk/782621 to your computer and use it in GitHub Desktop.
Save minrk/782621 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
"""
zmq_cli - 0MQ Server interruptability test case, client module.
"""
import zmq
def run(port):
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:%d" % port)
print "Sending test."
socket.send("test")
reply = socket.recv()
print "Got reply: %s." % repr(reply)
print "Sending EXIT."
socket.send("EXIT")
reply = socket.recv()
print "Got reply: %s." % repr(reply)
socket.close()
context.term()
if __name__ == "__main__":
run(54321)
#!/usr/bin/python
"""
zmq_serv - 0MQ Server interruptability test case.
Symptoms: The server does not stop immediately when I try to interrupt
it with ^C. If I subsequently send data to it from a client, the
server does stop with a KeyboardInterrupt exception at
'self.socket.recv()'.
This test case does seem to respect SIGTERM from outside, such as from
the 'kill' command.
"""
import zmq
import time
import sys
class Server(object):
"""
Simple 0MQ REQ/REP server. It replies to messages, and stops when
it gets the "EXIT" message.
"""
def __init__(self, port):
self.port = port
self.context = zmq.Context()
def run(self):
"""
Run the REQ/REP server.
"""
self.socket = self.context.socket(zmq.REP)
self.socket.bind("tcp://*:%d" % self.port)
print "Listening for messages."
while True:
message = self.socket.recv()
print "Received %d bytes." % len(message)
try:
reply = self.handle(message)
self.socket.send(reply)
except Exception as e:
self.socket.send("ERROR: %s." % str(e))
def handle(self, message):
"""
Handle the incoming message. Return an appropriate reply.
"""
if message == "EXIT":
self.stop()
return "Hello, %s!" % message
def stop(self):
"""
Stop the server, terminating the 0MQ context.
"""
self.socket.send('EXITING')
self.socket.close()
self.context.term()
sys.exit(0)
if __name__ == "__main__":
s = Server(54321)
s.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment