pyzmq的4种模式(REP/REQ)笔记 博客分类: python pythonzmq
程序员文章站
2024-02-23 11:59:10
...
REP/REQ模式就是最常见的Client/Server模式,zmq有亮点,翻译下:
特点 1. 和pair模式不同的是这种模式下客户端socket可以连接多个server
2. 客户端请求会被交替发送到server组的server
要注意的2个地方:
1. 客户端的 socket zmq.REQ 发送后会被阻塞直到新消息到来
2. 服务端的 socket zmq.REP 会阻塞直到新请求到来
然后保证:Each Request/Reply is paired and has to be successful.
然后这样子就负载均衡了啊啊,真是幸福来的太快
代码如下,改了一点点:
client:
import zmq import sys import time port = '5556' port,port1,client_name= sys.argv[1:] context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect('tcp://localhost:%s'%port) if port1: socket.connect('tcp://localhost:%s'%port1) for i in range(10): socket.send('client %s send message %d'%(client_name,i)) msg = socket.recv() print msg
server:
import zmq import sys import time port = '5556' server_name = '' port,server_name = list(sys.argv[1:]) context = zmq.Context() socket = context.socket(zmq.REP) socket.bind('tcp://*:%s'%port) print 'start listen:',port while True: message = socket.recv() print 'recieve request:',message time.sleep(1) socket.send('reply from server:%s port:%s'%(server_name,port))
run起来,
>>>python repreq-server.py 6665 server01 >>>python repreq-server.py 6666 server02 >>>python repreq-client.py 6665 6666 client01 >>>python repreq-client.py 6665 6666 client02
发现果然是在交替调用2个server
然后告诫诸位:
.... socket.send ("Hello") socket.send ("Hello1") .... Error: zmq.core.error.ZMQError: Operation cannot be accomplished in current state 这样子是不行的,不能乱来 另外发现:客户端send后,如果服务器挂了,它还是照等不误,这个以后要注意着点