其他分享
首页 > 其他分享> > ZeroMQ用法

ZeroMQ用法

作者:互联网

ZeroMQ用法

介绍

号称最快消息队列

在线安装

Ubuntu/Debian/Mint

apt-get install libczmq-dev

Fedora

dnf install czmq-devel

OSX

brew install czmq

Windows

#生成32位动态库
.\vcpkg.exe install czmq
#生成65位静态库
.\vcpkg.exe install czmq:x64-windows-static

源码安装

直接cmake外部构建,然后make三部曲

Demo

server

#include <iostream>
#include <cstring>
#include <zmq.h>
#include <assert.h>

int main()
{
    void* context = zmq_ctx_new();
    void* responder = zmq_socket(context, ZMQ_REP);
    int rc = zmq_bind(responder, "tcp://*:33333");
    if(rc != 0)
    {
        perror("zmq_bind err:");
        return -1;
    }

    while(1)
    {
        char buf[1024] = { 0 };
        zmq_recv(responder, buf, sizeof(buf), 0);

        std::cout << buf << std::endl;

        zmq_send(responder, buf, strlen(buf), 0);
    }

    zmq_close(responder);
    zmq_ctx_destroy(context);

    return 0;
}

client

#include <iostream>
#include <cstring>
#include <zmq.h>
#include <assert.h>
#include <unistd.h>

int main()
{
    void* context = zmq_ctx_new();
    void* requester = zmq_socket(context, ZMQ_REQ);
    int rc = zmq_connect(requester, "tcp://127.0.0.1:33333");
    if(rc != 0)
    {
        perror("zmq_connect err:");
        return -1;
    }

    for(int i = 0; i < 10; i++)
    {
        char buf[1024] = { 0 };
        sprintf(buf, "hello zmq %d", i+1);
        zmq_send(requester, buf, strlen(buf), 0);

        memset(buf, 0, sizeof(buf));
        zmq_recv(requester, buf, sizeof(buf), 0);
        std::cout << buf << std::endl;

        sleep(1);
    }

    zmq_close(requester);
    zmq_ctx_destroy(context);

    return 0;
}

标签:zmq,context,int,用法,install,ZeroMQ,include,buf
来源: https://blog.csdn.net/a13235463799/article/details/120453538