本人在centos下安装zeromq
1.下载最新版的zeromq
http://download.zeromq.org/
2 解压
tar -xvf zeromq-3.1.0-beta.tar.gz
3 运行configure
./configure --prefix=/data/zeromq (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 小于等于版本。
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);
// Socket to talk to clients
void *responder = zmq_socket (context, ZMQ_REP);
zmq_bind (responder, "tcp://127.0.0.1:5566");
printf("binding on port 5566.\nwaiting client send message...\n");
while (1) {
// Wait for next request from client
zmq_msg_t request;
zmq_msg_init (&request);
char buf[32];
zmq_recv (responder,buf, &request, 0);
int size = zmq_msg_size (&request);
char *string = malloc (size + 1);
memset(string,0,size+1);
memcpy (string, zmq_msg_data (&request), size);
printf ("Received Hello string=[%s]\n",string);
free(string);
zmq_msg_close (&request);
// Do some ‘work‘
sleep (1);
// Send reply back to client
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);
}
// 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>
int main ()
{
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://127.0.0.1:5566");
int request_nbr;
for (request_nbr = 0; request_nbr != 10; request_nbr++)
{
zmq_msg_t request;
zmq_msg_init_data (&request, "Hello", 6, NULL, NULL);
printf ("Sending request %d...\n", request_nbr);
zmq_send (requester, &request, 0,0);
printf("send over") ;
zmq_msg_close (&request);
zmq_msg_t reply;
zmq_msg_init (&reply);
zmq_recv (requester, &reply, 0,0);
printf ("Received reply %d: [%s]\n", request_nbr, (char *) zmq_msg_data (&reply));
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