ZeroMQ是一个消息队列网络库,实现网络常用技术封装。在C/S中实现了三种模式,这段时间用python简单实现了一下,感觉python虽然灵活。但是数据处理不如C++自由灵活。

 

1.Request-Reply模式:

客户端在请求后,服务端必须回响应

server:

 1 #!/usr/bin/python
 2 #-*-coding:utf-8-*-
 3 import time
 4 import zmq
 5 
 6 context = zmq.Context()
 7 socket = context.socket(zmq.REP)
 8 socket.bind("tcp://*:5555")
 9 
10 while True:
11     message = socket.recv()
12     print message
13     #time.sleep(1)
14     socket.send("server response!")

client:

 1 #!/usr/bin/python
 2 #-*-coding:utf-8-*-
 3 
 4 import zmq
 5 import sys
 6 
 7 context = zmq.Context()
 8 socket = context.socket(zmq.REQ)
 9 socket.connect("tcp://localhost:5555")
10 
11 while(True):
12     data = raw_input("input your data:")
13     if data == 'q':
14         sys.exit()
15 
16     socket.send(data)
17 
18     response = socket.recv();
19     print response

 

2.Publish-Subscribe模式:

广播所有client,没有队列缓存,断开连接数据将永远丢失。client可以进行数据过滤。

server:

 1 #!/usr/bin/python
 2 #-*-coding:utf-8-*-
 3 
 4 import zmq 
 5 context = zmq.Context()  
 6 socket = context.socket(zmq.PUB)  
 7 socket.bind("tcp://127.0.0.1:5000")  
 8 while True:  
 9     msg = raw_input('input your data:') 
10     socket.send(msg)

client:

 1 #!/usr/bin/python
 2 #-*-coding:utf-8-*-
 3 
 4 import time
 5 import zmq  
 6 context = zmq.Context()  
 7 socket = context.socket(zmq.SUB)  
 8 socket.connect("tcp://127.0.0.1:5000")  
 9 socket.setsockopt(zmq.SUBSCRIBE,'') 
10 while True:  
11     print  socket.recv() 

 

3.Parallel Pipeline模式:

由三部分组成,push进行数据推送,work进行数据缓存,pull进行数据竞争获取处理。区别于Publish-Subscribe存在一个数据缓存和处理负载。

当连接被断开,数据不会丢失,重连后数据继续发送到对端。


server:

 1 #!/usr/bin/python
 2 #-*-coding:utf-8-*-
 3 
 4 import zmq
 5 
 6 context = zmq.Context()
 7 
 8 socket = context.socket(zmq.PULL)
 9 socket.bind('tcp://*:5558')
10 
11 while True:
12     data = socket.recv()
13     print data

work:

 1 #!/usr/bin/python
 2 #-*-coding:utf-8-*-
 3 
 4 import zmq
 5 
 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 while True:
15     data = recive.recv()
16     sender.send(data)

client:

 1 #!/usr/bin/python
 2 #-*-coding:utf-8-*-
 3 
 4 import zmq
 5 import time
 6 
 7 context = zmq.Context()
 8 socket = context.socket(zmq.PUSH)
 9 
10 socket.bind('tcp://*:5557')
11 
12 while True:
13     data = raw_input('input your data:')
14     socket.send(data)

 

消息结构:
在每个消息buff前均会自带一个buff长度