Qt ZMQ通信效率测试

1、zmq相关库编译:https://www.cnblogs.com/tyche116/p/12102761.html

cmake后打开ZeroMQ.sln解决方案,在解决方案配置以及解决方案平台选择需要编译的版本后,右键仅生成libzmq项目,即可在bin及lib中生成生成对应的dll,lib.

 2、Qt中测试所编译zmq是否正确可用

1)新建qt项目;

2)pro项目文件中添加依赖路径及依赖文件:

LIBS += -L$$PWD/../ZMQ/lib/Release -llibzmq-v140-mt-4_3_2
INCLUDEPATH += $$PWD/../ZMQ/include
DEPENDPATH += $$PWD/../ZMQ/include

3)pro项目文件添加 CONFIG += console 打开调试信息输出(命令行)窗口;

4)将编译生成的zmq dll复制到可执行文件exe目录下;

5)测试代码及测试结果:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "zmq.h"

#include <iostream>

#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    int a,b,c;
    zmq_version(&a,&b,&c);
    std::cout << "zmq-version:" << a << "-" << b << "-" << c;
}

MainWindow::~MainWindow()
{
    delete ui;
}

6)编译正确且可以正常使用.

3、进程间通信测试

1)新建两个工程 server跟client

2)测试代码编写

server端代码

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "zmq.h"
#include <QThread>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    server();
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::server(void) { //Socket to talk to clients void *context = zmq_ctx_new (); void *responder = zmq_socket (context, ZMQ_REP); int rc = zmq_bind (responder, "tcp://*:5555"); assert (rc == 0); while (1) { char buffer [20]; const char * sendMsg = "[server]"; int bytes = zmq_recv (responder, buffer, 20, 0); buffer[bytes] = '\0'; printf ("Server have received %d bytes == \"%s\"\n",bytes,buffer); QThread::msleep (1); // Do some 'work' zmq_send (responder, sendMsg, strlen(sendMsg), 0); } }

client端代码

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "zmq.h"
#include <QThread>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    client();
}

MainWindow::~MainWindow()
{
    delete ui;
}

bool MainWindow::client()
{
    printf("Connecting to server...\n");

        void * context = zmq_ctx_new();
        void * socket = zmq_socket(context, ZMQ_REQ);
        zmq_connect(socket, "tcp://localhost:5555");

        for(int i = 0; i < 10; ++i)
        {
            char buffer[20];
            const char * snedMsg = "[client]";
            int bytes = zmq_send(socket, snedMsg, strlen(snedMsg), 0);

            bytes = zmq_recv(socket, buffer, 20, 0);
            buffer[bytes] = '\0';
            printf ("Client have received %d bytes == \"%s\"\n",bytes,buffer);

        }

        zmq_close(socket);
        zmq_ctx_destroy(context);

        return true;
}

3)分别编译并在同一台电脑上打开

posted @ 2020-06-23 08:59  鸡鸣昧旦  阅读(1734)  评论(0编辑  收藏  举报