1.Request-Reply模式:
客户端在请求后,服务端必须回响应
server:
#!/usr/bin/python#-*-coding:utf-8-*-
importtimeimportzmq
context=zmq.Context()
socket=context.socket(zmq.REP)
socket.bind("tcp://*:5555")whileTrue:
message=socket.recv()print(message)#time.sleep(1)
socket.send("server response!")
client:
#!/usr/bin/python#-*-coding:utf-8-*-
importzmqimportsys
context=zmq.Context()
socket=context.socket(zmq.REQ)
socket.connect("tcp://localhost:5555")while(True):
data= raw_input("input your data:")if data == 'q':
sys.exit()
socket.send(data)
response=socket.recv();print(response)
2.Publish-Subscribe模式:
广播所有client,没有队列缓存,断开连接数据将永远丢失。client可以进行数据过滤。
server:
#!/usr/bin/python#-*-coding:utf-8-*-
importzmq
context=zmq.Context()
socket=context.socket(zmq.PUB)
socket.bind("tcp://127.0.0.1:5000")whileTrue:
msg= raw_input('input your data:')
socket.send(msg)
client:
#!/usr/bin/python#-*-coding:utf-8-*-
importtimeimportzmq
context=zmq.Context()
socket=context.socket(zmq.SUB)
socket.connect("tcp://127.0.0.1:5000")
# 这里设置的是过滤条件,不然无法收到消息
socket.setsockopt(zmq.SUBSCRIBE,'')whileTrue:print socket.recv()
3.Parallel Pipeline模式:
由三部分组成,push进行数据推送,work进行数据缓存,pull进行数据竞争获取处理。区别于Publish-Subscribe存在一个数据缓存和处理负载。
当连接被断开,数据不会丢失,重连后数据继续发送到对端。
server:
#!/usr/bin/python#-*-coding:utf-8-*-
importzmq
context=zmq.Context()
socket=context.socket(zmq.PULL)
socket.bind('tcp://*:5558')whileTrue:
data=socket.recv()print data
work:
1 #!/usr/bin/python
2 #-*-coding:utf-8-*-
3
4 importzmq5
6 context =zmq.Context()7
8 recive =context.socket(zmq.PULL)9 recive.connect('tcp://127.0.0.1:5557')10
11 sender =context.socket(zmq.PUSH)12 sender.connect('tcp://127.0.0.1:5558')13
14 whileTrue:15 data =recive.recv()16 sender.send(data)
client:
#!/usr/bin/python#-*-coding:utf-8-*-
importzmqimporttime
context=zmq.Context()
socket=context.socket(zmq.PUSH)
socket.bind('tcp://*:5557')whileTrue:
data= raw_input('input your data:')
socket.send(data)
消息结构:
在每个消息buff前均会自带一个buff长度