Zeromq:如何在C访问的TCP消息++(Zeromq: How to access tcp me

2019-07-29 17:43发布

我是一个新的以ZeroMQ,让我的方式,通过回声客户端 - 服务器模式(请求 - 应答)的C ++你好世界的例子。 服务器是这样的:

//
// 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’

这同样适用于正在发送消息的客户端。 我没有找到一个方法来显示真正的消息...

Answer 1:

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其他一些有用的例子。



Answer 2:

我发现,下面我想要做什么:

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规则...



Answer 3:

虽然我认为我们需要去通过引导才可以写出优雅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);

然而,这种解决方案并不指定接收到的数据的长度,按照上述尼古拉Koudelia的方式,我做了接收数据的字符串:

 std::cout << "Received request: [" << std::string(static_cast<char*>(request.data()), request.size())  << "]" << std::endl;


文章来源: Zeromq: How to access tcp message in c++
标签: c++ tcp zeromq