16

我是 ZeroMQ 的新手,并通过 C++ hello-world 示例回显客户端-服务器模式(请求-回复)。服务器看起来像:

//
// Hello World server in C++
// Binds REP socket to tcp://*:5555
// Expects "Hello" from client, replies with "World"
//
#include <zmq.hpp>
#include <string>
#include <iostream>
#include <unistd.h>

int main () {
    // Prepare our context and socket
    zmq::context_t context (1);
    zmq::socket_t socket (context, ZMQ_REP);
    socket.bind ("tcp://*:5555");

    while (true) {
        zmq::message_t request;

        // Wait for next request from client
        socket.recv (&request);
        std::cout << "Received Hello" << std::endl;

        // Do some 'work'
        sleep (1);

        // Send reply back to client
        zmq::message_t reply (5);
        memcpy ((void *) reply.data (), "World", 5);
        socket.send (reply);
    }
    return 0;
}

现在我的问题是:如何访问/读取 socket.recv() 的真实数据?试:

 std::cout << request << std::endl;

导致错误消息:

 error: no match for ‘operator<<’ in ‘std::operator<< [with _Traits = 
 std::char_traits<char>](((std::basic_ostream<char, std::char_traits<char> >&)
 (& std::cout)), ((const char*)"Received Hello")) << request’

发送消息的客户端也是如此。我找不到显示真实信息的方法...

4

3 回答 3

45

hello world 示例只进行了一半并输出硬编码值:

std::cout << "Received Hello" << std::endl;

打印实际响应可以如下完成:

zmq::message_t reply;
socket.recv (&reply);

std::string rpl = std::string(static_cast<char*>(reply.data()), reply.size());

std::cout << rpl << std::endl;

zhelpers.hpp 中还有一些其他有用的示例。

于 2012-06-10T07:35:35.587 回答
1

我发现以下内容可以满足我的要求:

zmq::message_t request (msglen);
memcpy ( (void *) request.data(), myMessage, msglen);
char * requestmsg = new char [msglen];
memcpy (requestmsg, request.data(), request.size());
requestsocket.send (request);
std::cout << "Sending " <<  requestmsg << std::endl;

其中 msglen 是 int 类型,而 myMessage 是 const char * tyoe。以这种方式,服务器接收到人类可读的消息。希望这不违反任何 zeromq 规则......

于 2012-06-12T12:18:19.570 回答
1

虽然我认为我们需要通过指南才能编写优雅的 ZeroMQ 代码。我从HELLO WORLD示例中找到了几行简单的代码,用于提取从套接字接收的数据并发送回响应:

    zmq::message_t request;
    socket.recv (&request);
    std::cout << "Received request: [" << (char*) request.data() << "]" << std::endl;
    //  Do some 'work'
    Sleep (1);
    //  Send reply back to client
    zmq::message_t reply (6);
    memcpy ((void *) reply.data (), "World", 6);
    socket.send (reply);

但是,这个解决方案没有指定接收数据的长度,按照上面Nikolai Koudelia的方式,我为接收数据创建了一个字符串:

 std::cout << "Received request: [" << std::string(static_cast<char*>(request.data()), request.size())  << "]" << std::endl;
于 2016-03-28T06:48:16.207 回答