Windows下VS2008使用ZeroMQ说明
一、下载ZeroMQ
二、编译ZeroMQ库文件
解压zeromq-4.0.3.zip文件,进入builds\msvc目录,用VS打开*.sln工程文件,编译生成解决方案。编译完成后,会在lib目录下生成dll和lib文件
三、编写简单的测试工程
用VS新建2个项目,一个是server端,一个是client端
将ZeroMQ源码项目的include目录下的两个文件“zmq.h”,“zmq_utils.h”拷贝至自己新建的工程
将ZeroMQ源码项目的lib目录下的两个文件“libzmq.dll”,“libzmq.lib”拷贝至自己新建的工程
将文件“zmq.h”,“zmq_utils.h”和“libzmq.lib”添加进自己新建的项目。
client端代码:
#include
#include
#include
#include "zeroMQ/zmq.h"
#include "zeroMQ/zmq_utils.h"
int main(int argc,char** argv)
{
//zeroMQ相关变量
void * m_context;
void * m_subscriber;
char m_pubAddr[64];
m_context = zmq_init (1);
m_subscriber = zmq_socket (m_context, ZMQ_SUB);
//订阅
char * puberIP = "127.0.0.1";
WORD puberPort = 8585;
memset(m_pubAddr,0,sizeof(m_pubAddr));
sprintf(m_pubAddr,"tcp://%s:%d",puberIP,puberPort);
//zmq_connect (m_subscriber, "tcp://localhost:5556");
zmq_connect (m_subscriber, m_pubAddr);
int ret = zmq_setsockopt (m_subscriber, ZMQ_SUBSCRIBE, NULL, 0);
while(1)
{
BYTE buf[1024] = {0};
DWORD buflen = sizeof(buf);
DWORD gotLen = zmq_recv(m_subscriber,buf,buflen,0);
printf("收到发布信息:%s\n",buf);
}
zmq_close (m_subscriber);
zmq_term (m_context);
return 0;
}
6.server端代码:
#include
#include
#include
#include "zeroMQ/zmq.h"
#include "zeroMQ/zmq_utils.h"
int main(int argc,char** argv)
{
char pubLocalAddr[64] = {0};
sprintf(pubLocalAddr,"tcp://*:%d",8585);
//zeroMQ相关变量
void * m_context;
void * m_publisher;
m_context = zmq_init (1);
m_publisher = zmq_socket (m_context, ZMQ_PUB);
zmq_bind (m_publisher, pubLocalAddr);
char *msg = "1231321";
while(1)
{
DWORD sendlen = zmq_send(m_publisher,msg,strlen(msg),0);
printf("发布信息:%s\n",msg);
Sleep(1000);
}
zmq_close (m_publisher);
zmq_term (m_context);
return 1;
}