欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

zeromq的使用(windows)

程序员文章站 2022-05-09 10:56:50
...

注:本文说的是windows平台的使用

1.官网下载源码:http://zeromq.org/intro:get-the-software

下载stable release is v4.1.6

zeromq的使用(windows)

 2.vs2013进行编译lib库和dll(只编译libzmq工程即可)

找到路径:zeromq-4.1.6\builds\msvc\vs2013,用vs2013打开libzmq.sln。

zeromq的使用(windows)

直接编译libzmq会报错:

LINK : fatal error LNK1104: cannot open file 'libsodium.lib'

将libsodium设置为不链接:

zeromq的使用(windows)

 编译成功,编译后的文件(以win32 Releasewei)在zeromq-4.1.6\bin\Win32\Release\v120\dynamic下:

zeromq的使用(windows)

3.实战

将lib文件和头文件zmq.h、zmq_utils.h引入工程

(1)发布

// pub.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
#include"zmq.h"
#include"zmq_utils.h"

int main() {
	void *context = zmq_ctx_new();
	void *publisher = zmq_socket(context, ZMQ_PUB);
	zmq_bind(publisher, "tcp://*:9998");
	char sendbuf[64] = {0};
	int cnt = 0;
	while (cnt < 1000)
	{
		sprintf_s(sendbuf, "msg消息----%d", cnt++);
		std::cout << "msg消息----" << cnt << std::endl;
		zmq_send(publisher, sendbuf, strlen(sendbuf), 0);
		Sleep(1000);
		
	}
	std::cout << "publisher over!" << std::endl;
	zmq_close(publisher);
	zmq_ctx_destroy(context);
	getchar();
	return 0;
}

(2)订阅

// sub.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
#include"zmq.h"
#include"zmq_utils.h"

int main(void)
{
	void *context = zmq_ctx_new();
	void *subscriber = zmq_socket(context, ZMQ_SUB);

	zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, "", 0);
	zmq_connect(subscriber, "tcp://127.0.0.1:9998");
	while(1)
	{
		char recvbuf[64] = {0};
		int ret = zmq_recv(subscriber, recvbuf, 64, ZMQ_DONTWAIT);//ZMQ_DONTWAIT表示zmq_recv设置为非阻塞
		if (ret == -1)
		{
			if (errno == EAGAIN) continue;
			else
			{
				std::cout << "接收错误"<< std::endl;
				break;
			}
		}
			std::cout << recvbuf << std::endl;
	}
	zmq_close(subscriber);
	zmq_ctx_destroy(context);
	getchar();
	return 0;
}

zeromq的使用(windows)

 

 

API:https://www.cnblogs.com/fengbohello/p/4230135.html