python 3.x - Set identity to several ZMQ servers, binded to same port -
i implementing zmq dealer-router pattern in python 3.4. code zmq guide core of program.
sets identity each client (ex. 1,2,3,4). however, if start same number of server workers, not paired clients. 1 server worker may respond clients different identities.
question is: how set identities each server worker, server worker 1 interacts client 1? more precisely, need 4 clients interacting 4 server workers via 1 single port in paired manner.
i answer own question.
enough modify previous code set paired interactions:
1. pass id parameter in servertask class set server worker identity
2. change backend dealer router
whole system interacts in asynchronous pattern. i'll post whole script:
import zmq import sys import threading import time random import randint, random def tprint(msg): """like print, won't newlines confused multiple threads""" sys.stdout.write(msg + '\n') sys.stdout.flush() class clienttask(threading.thread): """clienttask""" def __init__(self, id): self.id = id threading.thread.__init__ (self) def run(self): context = zmq.context() socket = context.socket(zmq.dealer) identity = str(self.id) socket.identity = identity.encode('ascii') socket.connect('tcp://localhost:5570') print('client %s started' % (identity)) poll = zmq.poller() poll.register(socket, zmq.pollin) reqs = 0 in range(3): reqs = reqs + 1 print('client %s sent req #%d..' % (identity, reqs)) socket.send_string(u'request #%d' % (reqs)) in range(3): sockets = dict(poll.poll(1000)) if socket in sockets: msg = socket.recv() tprint('client %s received: %s' % (identity, msg)) socket.close() context.term() class servertask(threading.thread): """servertask""" def __init__(self): threading.thread.__init__ (self) def run(self): context = zmq.context() frontend = context.socket(zmq.router) frontend.bind('tcp://*:5570') backend = context.socket(zmq.router) backend.bind('inproc://backend') workers = [] in range(1,4): worker = serverworker(context, i) worker.start() workers.append(worker) zmq.proxy(frontend, backend) frontend.close() backend.close() context.term() class serverworker(threading.thread): """serverworker""" def __init__(self, context, id): threading.thread.__init__ (self) self.context = context self.id = id def run(self): worker = self.context.socket(zmq.dealer) identity = str(self.id) worker.connect('inproc://backend') tprint('worker %s started' % identity) in range(3): client_ident, msg = worker.recv_multipart() tprint('worker %s received %s %s' % (identity, msg, client_ident)) in range(2): time.sleep(1. / (randint(1,10))) worker.send_multipart([client_ident, msg]) worker.close() def main(): """main function""" server = servertask() server.start() in range(1,4): client = clienttask(i) client.start() server.join() if __name__ == "__main__": main()
Comments
Post a Comment