zmq简介
ZMQ(ØMQ、ZeroMQ, 0MQ)看起来像是一套嵌入式的网络链接库,但工作起来更像是一个并发式的框架。它提供的套接字可以在多种协议中传输消息,如线程间、进程间、TCP、广播等。你可以使用套接字构建多对多的连接模式,如扇出、发布-订阅、任务分发、请求-应答等。ZMQ的快速足以胜任集群应用产品。它的异步I/O机制让你能够构建多核应用程序,完成异步消息处理任务。ZMQ有着多语言支持,并能在几乎所有的操作系统上运行。ZMQ是iMatix公司的产品,以LGPL开源协议发布。
zmq安装
系统环境
[root@node1 tmpdir]# cat /etc/redhat-release 
CentOS Linux release 7.1.1503 (Core)
安装zmq和python-zmq
$ yum -y install zeromq3
$ yum -y install cppzmq-devel
$ yum -y install python-zmq
zmq简单使用
zmq有着多语言支持,这里的测试代码是使用的python和c++。
服务端代码
python版server.py
#coding: utf-8
import zmq  
import time  
context = zmq.Context()  
socket = context.socket(zmq.REP)  
socket.bind("tcp://192.168.10.131:5555")  
count = 0  
while True:  
    message = socket.recv()  
    count += 1 
    print "Receive request: %s, %s" % (message, count)
    time.sleep(1)  
    socket.send("World")
c++版server.cpp(编译命令: g++ -g zmq_server.cpp -lzmq)
#include <string>
#include <iostream>
#include <unistd.h>
#include "./zmq.hpp"
int main () {
    zmq::context_t context(1);
    zmq::socket_t socket(context, ZMQ_REP);
    socket.bind("tcp://127.0.0.1:5555");
    while(true){
        zmq::message_t request;
        socket.recv(&request);
        std::cout << "收到 Hello" << std::endl;
        sleep(1);
        zmq::message_t reply(5);
        memcpy((void *)reply.data(), "World", 5);
        socket.send(reply);
    }
    return 0;
}
客户端client.py代码
#coding: utf-8
import zmq  
context = zmq.Context()  
print "Connecting to hello world server..."  
socket = context.socket(zmq.REQ)  
socket.connect("tcp://192.168.10.131:5555")  
for request in range (1,10):  
    print "Sending request %s ..." % request  
    socket.send("Hello") 
    message = socket.recv() 
    print "Receives reply [%s]" % message 
结果展示
- 启动server.py或则server.cpp编译出来的可执行文件
- 启动client.py文件,结果若下所示:
client端输出信息:
Connecting to hello world server...
Sending request 1 ...
Receives reply [World]
Sending request 2 ...
Receives reply [World]
Sending request 3 ...
Receives reply [World]
Sending request 4 ...
Receives reply [World]
Sending request 5 ...
Receives reply [World]
Sending request 6 ...
Receives reply [World]
Sending request 7 ...
Receives reply [World]
Sending request 8 ...
Receives reply [World]
Sending request 9 ...
Receives reply [World]
server端输出信息:
收到 Hello
收到 Hello
收到 Hello
收到 Hello
收到 Hello
收到 Hello
收到 Hello
收到 Hello
收到 Hello
以上以最简单的方式演示了zeroMQ的使用,可以让初次接触的开发人员快速理解和上手,以便以此为基础开发出符合实际需求的功能。
 
		