我们使用一个例子来简单使用zeromq,感受一下客户端如何设定,服务器如何设定,模型如下:
本例子,客户端和接收端不停地互发消息,
服务端代码:
// 服务端代码 #include <zmq.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <assert.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://*:7766"); assert (rc == 0); while (true) { char buffer [10]; zmq_recv (responder, buffer, 10, 0); zmq_send (responder, "World", 5, 0); printf("sever_receive:--- %s\n",buffer); usleep (1000); // Do some ‘work‘ } return 0; }
#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:7766"); while(true) { char buffer [10]; zmq_send (requester, "Hello", 5, 0); zmq_recv (requester, buffer, 10, 0); printf("client_receive:--- %s\n",buffer); } zmq_close (requester); zmq_ctx_destroy (context); return 0; }
这个例子展示了zeromq的最基本用法,大家可以粘贴调试.
本文出自 “LinuxQt济南高新区” 博客,请务必保留此出处http://qtlinux.blog.51cto.com/3052744/1699073
原文:http://qtlinux.blog.51cto.com/3052744/1699073