1. 程式人生 > >zeromq客戶端伺服器hello world

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 <zmq.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>

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 <zmq.hpp>
#include <string>
#include <iostream>
#include <unistd.h>

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