ZeroMQ 的安装使用(Linux)

ZeroMQ 是一个分布式消息传递库,它提供了在各种传输中携带原子消息的套接字,如进程内,进程间,TCP和广播。可以使用pub-sub,任务分发和请求回复等模式连接N到N的套接字。它足够快,可以成为集群产品的结构。其异步I/O模型提供可扩展的多核应用程序,构建为异步消息处理任务。

下载安装

# 安装必备的包
$ sudo apt-get install libtool pkg-config build-essential autoconf automake
$ git clone https://github.com/zeromq/libzmq.git
$ mkdir build
$ cd build
$ cmake ..
$ sudo make -j4 install

# 安装libzmq的C++绑定

$ git clone [email protected]:zeromq/cppzmq.git
$ mkdir build
$ cd build
$ cmake ..
$ sudo make -j4 install

# 头文件路径 : /usr/local/include
# 库文件路径 : /usr/local/lib

使用

官方实例:

服务器端:

//
//  Hello World server in C++
//  Binds REP socket to tcp://*:5555
//  Expects "Hello" from client, replies with "World"
//
#include 
#include 
#include 
#ifndef _WIN32
#include 
#else
#include 

#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 
#include 
#include 

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 (request);

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

你可能感兴趣的:(Linux,网络)