1 Install
ubuntu 16.10上安装zeroMQ:
(1) 下载zeromq
wget https://github.com/zeromq/libzmq/releases/download/v4.2.1/zeromq-4.2.1.tar.gz
(2) 解压
tar -zxvf zeromq-4.2.1.tar.gz
(3) 编译安装
执行configure文件:./configure
编译: make
安装: make install
2 编写样例代码
server端代码:server.cpp
#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;
}
client端代码:client.cpp
#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;
}
makefile文件
.PHONY : clean all
CC = g++
BIN = client server
all: $(BIN)
client:
$(CC) $@.cpp -o $@ -lzmq -I./include -L./lib
server:
$(CC) $@.cpp -o $@ -lzmq -I./include -L./lib
clean:
rm $(BIN)
网友评论