Created
November 14, 2012 12:11
-
-
Save brookst/4071783 to your computer and use it in GitHub Desktop.
ZeroMQ REQ/REP test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python | |
"0MQ messaging test" | |
import zmq | |
CONTEXT = zmq.Context.instance() | |
def get_opts(): | |
"Get program options" | |
from argparse import ArgumentParser | |
parser = ArgumentParser() | |
arg = parser.add_argument | |
arg('-c', '--client', action = 'store_true', default=False, \ | |
help="Act as client") | |
arg('-s', '--server', action = 'store_true', default=False, \ | |
help="Act as server") | |
arg('-a', '--address', default="localhost", type=str, | |
help="Address to contact") | |
arg('-p', '--port', default=5555, type=int, | |
help="TCP port to use") | |
return parser.parse_args() | |
def respond(sock): | |
"Recieve a message and respond to it" | |
message = sock.recv() | |
response = "world" | |
sock.send(response) | |
print("Received '{0:s}', sent '{1:s}'.".format(message, response) ) | |
def request(sock): | |
"Send 'Hello' to remote port" | |
message = "Hello" | |
sock.send(message) | |
response = sock.recv() | |
print("Sent '{0:s}', recieved '{1:s}'".format(message, response) ) | |
def main(): | |
"Program code" | |
opts = get_opts() | |
if opts.client: | |
sock = CONTEXT.socket(zmq.REQ) | |
sock.bind("tcp://*:{0:d}".format(opts.port) ) | |
request(sock) | |
if opts.server: | |
sock = CONTEXT.socket(zmq.REP) | |
sock.connect("tcp://{0:s}:{1:d}".format(opts.address, opts.port) ) | |
while True: | |
respond(sock) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment