我在Python 3.4中实现了ZMQ DEALER-ROUTER模式。这个code from ZMQ guide是我的计划的核心。
它轻松地为每个客户设置身份(例如1,2,3,4)。但是,如果我启动相同数量的服务器工作程序,则它们不会与客户端配对。一个服务器工作者可以响应具有不同身份的客户端。
我的问题是:如何为每个服务器工作者设置身份,以便服务器工作者1仅与客户端1进行交互?更准确地说,我需要4个客户端通过一个端口与4个服务器工作者进行交互配对方式。
答案 0 :(得分:0)
我会回答我自己的问题。
只需稍微修改以前的代码即可设置成对的交互:
的 1。在ServerTask类中传递id参数以设置服务器工作者身份
2.将后端从DEALER更改为ROUTER
整个系统以异步模式进行交互。我将发布整个脚本:
import zmq
import sys
import threading
import time
from random import randint, random
def tprint(msg):
"""like print, but won't get newlines confused with 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
for i in range(3):
reqs = reqs + 1
print('Client %s sent req #%d..' % (identity, reqs))
socket.send_string(u'request #%d' % (reqs))
for i 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 = []
for i 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)
for i in range(3):
client_ident, msg = worker.recv_multipart()
tprint('Worker %s received %s from %s' % (identity, msg, client_ident))
for i 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()
for i in range(1,4):
client = ClientTask(i)
client.start()
server.join()
if __name__ == "__main__":
main()