linux zeromq
本人在centos下安装zeromq
1.下载最新版的zeromq
http://download.zeromq.org/
2 解压
tar -xvf zeromq-3.1.0-beta.tar.gz
3 运行configure
./configure --prefix=/data/zeromq PKG_CONFIG_PATH="/data/sodium/lib/pkgconfig/" (prefix 指定安装目录)
出现问题:
configure: error: Package requirements (libsodium >= 0.0.0) were not met
参考:
http://www.cnblogs.com/jim-hwg/p/4952349.html
这里最好使用
libsodium-1.0.3 小于等于版本。
cd /home/shengkaishan/software/libsodium-1.0.3
./configure --prefix=/data/sodium
make
make install
4. make
5. make install
c代码
server.c
#include <zmq.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> int main (void) { void *context = zmq_init (1); void *responder = zmq_socket (context, ZMQ_REP); zmq_bind(responder, "tcp://127.0.0.1:5566"); while (1) { // Wait for next request from client zmq_msg_t request; zmq_msg_init(&request); zmq_recvmsg(responder, &request, 0); //printf("Received client msg = [%s]\n", (char *)zmq_msg_data(&request)); #if 1 int size = zmq_msg_size(&request); char *msg = (char *)malloc(size + 1); memset(msg, 0, size+1); memcpy(msg, zmq_msg_data(&request), size); printf ("Received Client=[%s]\n", msg); free(msg); #endif zmq_msg_close(&request); // Do some 'work' sleep (1); // Send reply back to client zmq_msg_t reply; zmq_msg_init_data(&reply, "world", 6, NULL, NULL); zmq_sendmsg(responder, &reply, 0); zmq_msg_close(&reply); #if 0 zmq_msg_t reply; char res[128]={0}; snprintf(res, 127, "reply:%d", random()); zmq_msg_init_size(&reply, strlen(res)); memcpy(zmq_msg_data(&reply), res, strlen(res)); char buf2[32]; zmq_send(responder, buf2, &reply, 0); zmq_msg_close(&reply); #endif } // We never get here but if we did, this would be how we end zmq_close(responder); zmq_term(context); return 0; }
client.c
#include <zmq.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> int main () { void *context = zmq_init(1); void *requester = zmq_socket(context, ZMQ_REQ); zmq_connect (requester, "tcp://127.0.0.1:5566"); int request_nbr; for (request_nbr = 0; request_nbr != 10; request_nbr++) { zmq_msg_t request; zmq_msg_init_size(&request, 5); //memset(zmq_msg_data(&request), 'H', 5); //memcpy(zmq_msg_data(&request), "Hello", 5); zmq_msg_init_data(&request, "Hello", 5, NULL, NULL); zmq_sendmsg(requester, &request, 0); zmq_msg_close(&request); zmq_msg_t reply; zmq_msg_init(&reply); //zmq_recv(requester, &reply, 0,0); zmq_recvmsg(requester, &reply, 0); //printf ("Received reply %d: [%s]\n", request_nbr, (char *)zmq_msg_data(&reply)); #if 1 int size = zmq_msg_size(&reply); char *msg = (char *)malloc(size + 1); memset(msg, 0, size+1); memcpy(msg, zmq_msg_data(&reply), size); printf ("Received Server=[%s]\n", msg); free(msg); #endif zmq_msg_close(&reply); } zmq_close(requester); zmq_term(context); return 0; }
export LD_LIBRARY_PATH=/data/zeromq/lib/:$LD_LIBRARY_PATH
gcc server.c -o server -lzmq -L/data/zeromq/lib -I/data/zeromq/include
gcc client.c -o client -lzmq -L/data/zeromq/lib -I/data/zeromq/include