(1)下载ZeroMQ以及头文件zmq.hpp
ZeroMQ:http://download.zeromq.org/
zmq.hpp:https://github.com/zeromq/cppzmq/archive/master.zip
(2)编译生成动态库
1.解压
tar -xvf zeromq-4.1.2.tar.gz2.编译
cd zeromq-4.1.2 ./configure --prefix=/home/libdev/zmq --without-libsodium make && make install
则执行以下命令:
./configure --prefix=/home/libdev/zmq --without-libsodium3.示例以及编译、运行
服务端:Server
hwserver.cpp
#include <zmq.hpp> #include <string> #include <iostream> #include <unistd.h> int main () { // Prepare our context and socket zmq::context_t context (1); zmq::socket_t socket (context, ZMQ_REP); socket.bind ("tcp://*:5555"); while (true) { zmq::message_t request; // Wait for next request from client socket.recv (&request); std::cout << "Received Hello" << std::endl; // Do some 'work' sleep (1); // Send reply back to client zmq::message_t reply (5); memcpy ((void *) reply.data (), "World", 5); socket.send (reply); } return 0; }
客户端:Client
hwclient.cpp
<span style="font-size:18px;">// // Hello World client // Connects REQ socket to tcp://localhost:5555 // Sends "Hello" to server, expects "World" back // #include <zmq.h> #include <string.h> #include <stdio.h> #include <unistd.h> int main (void) { void *context = zmq_init (1); // Socket to talk to server printf ("Connecting to hello world server…\n"); 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++) { zmq_msg_t request; zmq_msg_init_size (&request, 5); memcpy (zmq_msg_data (&request), "Hello", 5); printf ("Sending Hello %d…\n", request_nbr); zmq</span><span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size:12px;">_msg</span></span><span style="font-size:18px;">_send (&request, requester, 0); zmq_msg_close (&request); zmq_msg_t reply; zmq_msg_init (&reply); zmq_msg_recv (&reply, requester, 0); printf ("Received World %d\n", request_nbr); zmq_msg_close (&reply); } zmq_close (requester); zmq_term (context); return 0; }</span>编译命令:
g++ -g -Wall -fPIC -I/home/libdev/zmq/include -L/home/libdev/zmq/lib -lzmq hwserver.cpp -o server
g++ -g -Wall -fPIC -I/home/libdev/zmq/include -L/home/libdev/zmq/lib -lzmq hwclient.cpp -o client
4.运行
./server
./client