zeromq客户端服务器hello world

我在这里用了最新版的zeromq4.2.0,照抄zguide上面的例子,居然报错,报错信息如下:

gcc -Wall -g hwclient.c -lzmq -o hwclient
hwclient.c: In function ‘main’:
hwclient.c:21:9: error: too few arguments to function ‘zmq_send’
         zmq_send (requester, &request, 0);
         ^~~~~~~~
In file included from hwclient.c:1:0:
/usr/local/include/zmq.h:430:16: note: declared here
 ZMQ_EXPORT int zmq_send (void *s, const void *buf, size_t len, int flags);
                ^~~~~~~~
hwclient.c:26:9: error: too few arguments to function ‘zmq_recv’
         zmq_recv (requester, &reply, 0);
         ^~~~~~~~
In file included from hwclient.c:1:0:
/usr/local/include/zmq.h:432:16: note: declared here
 ZMQ_EXPORT int zmq_recv (void *s, void *buf, size_t len, int flags);

然后去看zmq.h的源码,发现zmq_recv和zmq_send函数都有四个参数:

ZMQ_EXPORT int zmq_send (void *s, const void *buf, size_t len, int flags);
ZMQ_EXPORT int zmq_recv (void *s, void *buf, size_t len, int flags);

然后我在hwclient.c里面在这个两个函数参数里面都加了一个0,编译通过!
客户端用C语言实现:

//hwclient.c
#include 
#include 
#include 
#include 

int main (void)
{
    void *context = zmq_init (1);

    //  连接至服务端的套接字
    printf ("正在连接至hello world服务端...\n");
    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++) {
        zmq_msg_t request;
        zmq_msg_init_size (&request, 5);
        memcpy (zmq_msg_data (&request), "Hello", 5);
        printf ("正在发送 Hello %d...\n", request_nbr);
        zmq_send (requester, &request, 0,0);
        zmq_msg_close (&request);

        zmq_msg_t reply;
        zmq_msg_init (&reply);
        zmq_recv (requester, &reply, 0,0);
        printf ("接收到 World %d\n", request_nbr);
        zmq_msg_close (&reply);
    }
    zmq_close (requester);
    zmq_term (context);
    return 0;
}

客户端代码如下,用C++写的:

//hwserver.c
#include 
#include 
#include 
#include 

int main () {
    // 准备上下文和套接字
    zmq::context_t context (1);
    zmq::socket_t socket (context, ZMQ_REP);
    socket.bind ("tcp://*:5555");

    while (true) {
        zmq::message_t request;

        // 等待客户端请求
        socket.recv (&request);
        std::cout << "收到 Hello" << std::endl;

        // 做一些“处理”
        sleep (1);

        // 应答World
        zmq::message_t reply (5);
        memcpy ((void *) reply.data (), "World", 5);
        socket.send (reply);
    }
    return 0;
}

开两个terminal,一个./hwclient,一个./hwserver,结果如下:

./server
收到 Hello
收到 Hello
收到 Hello
收到 Hello
收到 Hello
收到 Hello
收到 Hello
收到 Hello
收到 Hello
收到 Hello
./hwclient
正在连接至hello world服务端...
正在发送 Hello 0...
接收到 World 0
正在发送 Hello 1...
接收到 World 1
正在发送 Hello 2...
接收到 World 2
正在发送 Hello 3...
接收到 World 3
正在发送 Hello 4...
接收到 World 4
正在发送 Hello 5...
接收到 World 5
正在发送 Hello 6...
接收到 World 6
正在发送 Hello 7...
接收到 World 7
正在发送 Hello 8...
接收到 World 8
正在发送 Hello 9...
接收到 World 9

你可能感兴趣的:(zeromq)