ZMQ笔记——入门

ZMQ笔记

ZMQ下载:

Ubuntu/Debian/Mint环境下:

apt-get install libzmq3-dev

入门例子:只要包含<zmq.hpp>即可

//
//  Hello World server in C++
//  Binds REP socket to tcp://*:5555
//  Expects "Hello" from client, replies with "World"
//
#include <zmq.hpp>
#include <string>
#include <iostream>
#ifndef _WIN32
#include <unistd.h>
#else
#include <windows.h>

#define sleep(n)	Sleep(n)
#endif

int main () {
    //  Prepare our context and socket
    zmq::context_t context (1);
    zmq::socket_t socket (context, ZMQ_REP);
    socket.bind ("tcp://*:5555");

    while (true) {
        zmq::message_t request;

        //  Wait for next request from client
        socket.recv (&request);
        std::cout << "Received Hello" << std::endl;

        //  Do some 'work'
    	sleep(1);

        //  Send reply back to client
        zmq::message_t reply (5);
        memcpy (reply.data (), "World", 5);
        socket.send (reply);
    }
    return 0;
}
//
//  Hello World client in C++
//  Connects REQ socket to tcp://localhost:5555
//  Sends "Hello" to server, expects "World" back
//
#include <zmq.hpp>
#include <string>
#include <iostream>

int main ()
{
    //  Prepare our context and socket
    zmq::context_t context (1);
    zmq::socket_t socket (context, ZMQ_REQ);

    std::cout << "Connecting to hello world server..." << std::endl;
    socket.connect ("tcp://localhost:5555");

    //  Do 10 requests, waiting each time for a response
    for (int request_nbr = 0; request_nbr != 10; request_nbr++) {
        zmq::message_t request (5);
        memcpy (request.data (), "Hello", 5);
        std::cout << "Sending Hello " << request_nbr << "..." << std::endl;
		//socket.send()
        socket.send (request);

        //  Get the reply.
        zmq::message_t reply;
        socket.recv (&reply);
        std::cout << "Received World " << request_nbr << std::endl;
    }
	socket.close();
    return 0;
}

ZMQ与传统TCP套接字的不同

  1. ZeroMQ套接字携带消息,如UDP,而不是像TCP那样的字节流。 ZeroMQ消息是长度指定的二进制数据.他们的设计针对性能进行了优化,因此会有些技巧。
  2. ZeroMQ套接字在后台线程中执行其I / O.这意味着无论您的应用程序正忙于执行什么操作,消息都会到达本地输入队列并从本地输出队列发送。
  3. 根据套接字类型,ZeroMQ套接字具有内置的一对N路由行为。

zmq_send()方法实际上并不将消息发送到套接字连接。它对消息进行排队,以便I / O线程可以异步发送它。除了一些例外情况外,它不会阻止。因此,当zmq_send()返回到您的应用程序时,不一定会发送消息。

ZeroMQ内置的模式有

  • Request-reply:它将一组客户端连接到一组服务。这是一个远程过程调用和任务分配模式
  • Pub-sub:它将一组发布者连接到一组订阅者。这是一种数据分布模式
  • Pipeline:它以扇出/扇入模式连接节点,可以有多个步骤和循环。这是一个并行的任务分发和收集模式
  • Exclusive pair:它专门连接两个插座。这是一个连接进程中两个线程的模式,不要与“普通”套接字对混淆。
发布了80 篇原创文章 · 获赞 68 · 访问量 7574

猜你喜欢

转载自blog.csdn.net/weixin_44048823/article/details/99644177
zmq