研究了一下,这个库神奇而优秀,自己理解定义为:高效、简炼、TCP/IP层以上网络的、进程间的、线程间的消息队列(Message Queue)。
官网:http://zeromq.org/
RFC:http://rfc.zeromq.org/
支持很多语言的版本,有些教程过期了,本人只是重新翻译,只有写过的人才知道如何优秀,所以懒的废话连篇讲道理什么的,大家需要的是实实在在的实践操作。
配置:windows 8.1 64+vs2013 update5+ZeroMQ 4.0.4
语言:c++
框架
服务端hwserver.cpp:
#include<zmq.h>
#include<iostream>
#include<thread>
#include<chrono>
using std::cout;
using std::endl;
int main()
{
void* pContext = zmq_ctx_new();
void* pRepSocket = zmq_socket(pContext, ZMQ_REP);
zmq_bind(pRepSocket, "tcp://*:5001");
cout << "server starting..." << endl;
while (true)
{
//接收消息;
zmq_msg_t msgIn;
zmq_msg_init(&msgIn);
zmq_msg_recv(&msgIn, pRepSocket, 0);
cout << "received:" << (char*)zmq_msg_data(&msgIn) << endl;
zmq_msg_close(&msgIn);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
//发送消息;
char buffer[] = "world";
int bufferSize = sizeof(buffer);
zmq_msg_t msgOut;
zmq_msg_init_size(&msgOut, bufferSize);
memcpy(zmq_msg_data(&msgOut), buffer, bufferSize);
zmq_msg_send(&msgOut, pRepSocket, 0);
zmq_msg_close(&msgOut);
}
zmq_close(pRepSocket);
zmq_ctx_term(pContext);
return 0;
}
客户端hwclient.cpp(差不多只是while循环反转-接收与发送)
#include<zmq.h>
#include<iostream>
#include<thread>
#include<chrono>
using std::cout;
using std::endl;
int main()
{
void* pContext = zmq_ctx_new();
void* pReqSocket = zmq_socket(pContext, ZMQ_REQ);
zmq_connect(pReqSocket, "tcp://localhost:5001");
cout << "client starting..." << endl;
while (true)
{
static int n = 0;
cout << "send hello..." << n++ <<"-----";
//发送消息;
char buffer[] = "hello";
int bufferSize = sizeof(buffer);
zmq_msg_t msgOut;
zmq_msg_init_size(&msgOut, bufferSize);
memcpy(zmq_msg_data(&msgOut), buffer, bufferSize);
zmq_msg_send(&msgOut, pReqSocket, 0);
zmq_msg_close(&msgOut);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
//接收消息;
zmq_msg_t msgIn;
zmq_msg_init(&msgIn);
zmq_msg_recv(&msgIn, pReqSocket, 0);
cout << "received:" << (char*)zmq_msg_data(&msgIn) << endl;
zmq_msg_close(&msgIn);
}
zmq_close(pReqSocket);
zmq_ctx_term(pContext);
return 0;
}
效果: