ZeroMq编译及REQ-REP模式代码

假设zZeroMq源码放在/home/zhangjian/mq/libzmq-4.2.0中,编译过程如下:
./configure --prefix=/home/zhangjian/mq/libzmq-4.2.0 --without-libsodium
make -j 8 && make install
将会在lib路径下生成libzmq.a和libzmq.so库

代码编译:
1、export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/zhangjian/mq/
2、如果代码需要libzmq.so.5库,那么可以做个软链接
3、g++ -g -Wall -fPIC -fpermissive -I/home/zhangjian/mq -L/home/在这里插入代码片zhangjian/mq -lzmq server.cpp -o server

附REQ-REP模式demo(代码来自书中)
client:

#include 
#include 
#include 

#include "zmq.h"

void client_recv_data(void *requester, int bufLen, char *pcRspBuf)
{
     
    zmq_msg_t reply;
    zmq_msg_init(&reply);
    zmq_msg_recv(&reply, requester, 0);

    memcpy(pcRspBuf, zmq_msg_data(&reply), bufLen);
    zmq_msg_close(&reply);

    return;
}

int main (void)
{
     
    void *context = zmq_ctx_new();

    // Socket to talk to server
    printf("Connecting to hello world server.\n");
    void *requester = zmq_socket (context, ZMQ_REQ);
    zmq_connect (requester, "tcp://localhost:5555");

    int request_nbr;
    for (request_nbr = 0; request_nbr != 10; request_nbr++)
    {
     
        char szSendBuf[10] = {
     0};
        snprintf(szSendBuf, sizeof(szSendBuf), "Hello_%03d", request_nbr);

        zmq_msg_t request;
        zmq_msg_init_data(&request, szSendBuf, strlen(szSendBuf), NULL, NULL);

        zmq_msg_send(&request, requester, 0);
        zmq_msg_close(&request);
        printf("Sending Hello Times:%d.\n", request_nbr);

        /* recv response data */
        char szRecvBuf[10] = {
     0};
        client_recv_data(requester, sizeof(szRecvBuf), szRecvBuf);
        printf("Times:%d Received replay:%s\n", request_nbr, szRecvBuf);

        sleep(1);
    }

    sleep(2);
    zmq_close(requester);
    zmq_term(context);

    return 0;
}

server:

#include 
#include 
#include 
#include 

#include "zmq.h"

void server_recv_data(void *requester, int bufLen, char *pcRspBuf)
{
     
    zmq_msg_t reply;
    zmq_msg_init(&reply);
    zmq_msg_recv(&reply, requester, 0);

    memcpy(pcRspBuf, zmq_msg_data(&reply), bufLen);
    zmq_msg_close(&reply);

    return;
}

int main ()
{
     
    // Prepare our context and socket
    void *context = zmq_ctx_new();
    void *responder = zmq_socket(context, ZMQ_REP);
    zmq_bind(responder, "tcp://*:5555");

    while (true)
    {
     
        char szRecvBuf[10] = {
     0};
        server_recv_data(responder, sizeof(szRecvBuf), szRecvBuf);

        printf("Server Received data:%s.\n", szRecvBuf);

        sleep(1);

        // Send reply back to client
        zmq_msg_t reply;
        zmq_msg_init_data(&reply, "World", 6, NULL, NULL);

        //zmq_msg_init_size(&reply, 5);
        //memcpy(zmq_msg_data(&reply), "World", strlen("World"));
        zmq_msg_send(&reply, responder, 0);

        zmq_msg_close(&reply);
    }

    zmq_close(responder);
    zmq_ctx_destroy(context);

    return 0;
}



你可能感兴趣的:(消息队列,c++)