武汉-带鱼

  • 主页
  • 所有文章
关于我

武汉-带鱼

  • 主页
  • 所有文章

zeroMQ使用

2021-02-24

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 

结果展示

  1. 启动server.py或则server.cpp编译出来的可执行文件
  2. 启动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的使用,可以让初次接触的开发人员快速理解和上手,以便以此为基础开发出符合实际需求的功能。

赏

谢谢你请我吃糖果

微信

扫一扫,分享到微信

微信分享二维码
根据ceph源码制作ceph RPM包
windows安装MySQL-python
© 2021 武汉-带鱼
Hexo Theme Yilia by Litten
  • 关于我
每天一点点。

QQ:1041315735
Email:1041315735@qq.com