linux下搭建ZeroMQ的C++环境------顺便看下ZeroMQ“请求/应答”模型的代码

972 篇文章 329 订阅
148 篇文章 34 订阅

       直接上菜:

 

       1.  下载并解压:

cd /home/ubuntu/taoge/zmq
下载地址:http://download.zeromq.org/
tar -xvf zeromq-4.1.2.tar.gz

       2.  编译并安装

cd zeromq-4.1.2
./configure --prefix=/home/ubuntu/taoge/zmq --without-libsodium
make && make install

      3. 写代码, 并编译运行(注意:如果编译通过,但运行缺库,就在shell中执行export LD_LIBRARY_PATH=/home/ubuntu/taoge/zmq/lib 即可)

cd /home/ubuntu/taoge/zmq/test
touch hwclient.cpp hwserver.cpp

g++ hwserver.cpp -g -Wall -fPIC -I/home/ubuntu/taoge/zmq/include -L/home/ubuntu/taoge/zmq/lib -lzmq -o server

g++ hwclient.cpp -g -Wall -fPIC -I/home/ubuntu/taoge/zmq/include -L/home/ubuntu/taoge/zmq/lib -lzmq -o client
ubuntu@VM-0-15-ubuntu:~/taoge/zmq/test$ ./server 
ubuntu@VM-0-15-ubuntu:~/taoge/zmq/test$ ./client 
recv:sending 0, heheda
recv:sending 1, heheda
recv:sending 2, heheda
recv:sending 3, heheda
recv:sending 4, heheda

       4. 附上代码:

         hwserver.cpp:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include "zmq.h"

int main ()
{
    void *context = zmq_ctx_new();
    void *s = zmq_socket(context, ZMQ_REP);
    int rc = zmq_bind(s, "tcp://*:5555");
    assert (rc == 0);
 
    while (1) 
    {
        char buffer[1024] = {0};
        zmq_recv(s, buffer, sizeof(buffer) - 1, 0);
        strcat(buffer, ", heheda");
        zmq_send(s, buffer, strlen(buffer) + 1, 0);
    }

    zmq_close(s);
    zmq_ctx_destroy(context);
    return 0;
}

        hwclient.cpp:

#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include "zmq.h"
 
int main (void)
{
    void *context = zmq_ctx_new();
    void *s = zmq_socket(context, ZMQ_REQ);
    zmq_connect(s, "tcp://localhost:5555");
 
    int i = 0;
    while(1) 
    {
        char buffer[1024] = {0};
        snprintf(buffer, sizeof(buffer), "sending %d", i);
        zmq_send(s, buffer, strlen(buffer) + 1, 0);
        zmq_recv(s, buffer, sizeof(buffer) - 1, 0);
        printf("recv:%s\n", buffer);
        i++;

        sleep(1);
    }

    zmq_close(s);
    zmq_ctx_destroy(context);

    return 0;
}

        

         自己玩一下, 可以看到, 即使先开启客户端端, 再开启服务端, 消息也不会丢失。

 

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值