直接上菜:
1. 下载并解压:
cd /home/ubuntu/taoge/zmq
下载地址:http://download.zeromq.org/
tar -xvf zeromq-4.1.2.tar.gz
2. 编译并安装
cd zeromq-4.1.2
./configure --prefix=/home/ubuntu/taoge/zmq --without-libsodium
make && make install
3. 写代码, 并编译运行(注意:如果编译通过,但运行缺库,就在shell中执行export LD_LIBRARY_PATH=/home/ubuntu/taoge/zmq/lib 即可)
cd /home/ubuntu/taoge/zmq/test
touch hwclient.cpp hwserver.cpp
g++ hwserver.cpp -g -Wall -fPIC -I/home/ubuntu/taoge/zmq/include -L/home/ubuntu/taoge/zmq/lib -lzmq -o server
g++ hwclient.cpp -g -Wall -fPIC -I/home/ubuntu/taoge/zmq/include -L/home/ubuntu/taoge/zmq/lib -lzmq -o client
ubuntu@VM-0-15-ubuntu:~/taoge/zmq/test$ ./server
ubuntu@VM-0-15-ubuntu:~/taoge/zmq/test$ ./client
recv:sending 0, heheda
recv:sending 1, heheda
recv:sending 2, heheda
recv:sending 3, heheda
recv:sending 4, heheda
4. 附上代码:
hwserver.cpp:
#include
#include
#include
#include
#include "zmq.h"
int main ()
{
void *context = zmq_ctx_new();
void *s = zmq_socket(context, ZMQ_REP);
int rc = zmq_bind(s, "tcp://*:5555");
assert (rc == 0);
while (1)
{
char buffer[1024] = {0};
zmq_recv(s, buffer, sizeof(buffer) - 1, 0);
strcat(buffer, ", heheda");
zmq_send(s, buffer, strlen(buffer) + 1, 0);
}
zmq_close(s);
zmq_ctx_destroy(context);
return 0;
}
hwclient.cpp:
#include
#include
#include
#include "zmq.h"
int main (void)
{
void *context = zmq_ctx_new();
void *s = zmq_socket(context, ZMQ_REQ);
zmq_connect(s, "tcp://localhost:5555");
int i = 0;
while(1)
{
char buffer[1024] = {0};
snprintf(buffer, sizeof(buffer), "sending %d", i);
zmq_send(s, buffer, strlen(buffer) + 1, 0);
zmq_recv(s, buffer, sizeof(buffer) - 1, 0);
printf("recv:%s\n", buffer);
i++;
sleep(1);
}
zmq_close(s);
zmq_ctx_destroy(context);
return 0;
}
自己玩一下, 可以看到, 即使先开启客户端端, 再开启服务端, 消息也不会丢失。