worker端
#include <zmq.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
int main (void)
{
printf ("Connecting to hello world server…\n");
void *context = zmq_ctx_new ();
void *requester = zmq_socket (context, ZMQ_REQ);
zmq_connect (requester, "tcp://localhost:5555");
int request_nbr;
for (request_nbr = 0; request_nbr != 10; request_nbr++) {
char buffer [10];
printf ("Sending Hello %d…\n", request_nbr);
zmq_send (requester, "Hello", 5, 0);
zmq_recv (requester, buffer, 10, 0);
printf ("Received World %d\n", request_nbr);
}
zmq_close (requester);
zmq_ctx_destroy (context);
return 0;
}
server side:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <zmq.h>
int main (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 [10];
zmq_recv (responder, buffer, 10, 0);
printf ("Received Hello\n");
sleep (1); // Do some 'work'
zmq_send (responder, "World", 5, 0);
}
return 0;
}
run:
g++ zmqserver.cpp -o zmqserverdemo -lzmq
//生成服务器文件,后面的lzmq一定要加。是一个链接zmq的核心库
g++ zmqworker.cpp -o zmqworker -lzmq
//生成worker端文件
//运行:开启两个终端
./zmqserverdemo
./zmqworker
Need to install the library:
git clone https://github.com/zeromq/libzmq
cd libzmq
./autogen.sh
./configure
make
sudo make check
sudo make install
sudo ldconfig
cd ..
In order to be able to use c++ for linking, the operations needed are:
git clone https://github.com/zeromq/cppzmq.git
cd cppzmq
sudo cp zmq.hpp /usr/local/include/
cd ..
//If you do not do this step, you may not find the zmq.hpp file