Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zeromq: How to access tcp message in c++

Tags:

c++

tcp

zeromq

I am a new-by to ZeroMQ and make my way through the C++ hello-world example of the echo client-server pattern (Request-Reply). The server looks like:

//
// 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;
}

Now my question: How can I access / read the real data that socket.recv() ? Trying:

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

resulted in an error message:

 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’

The same goes for the client side that is sending the message. I don't find a way to display the real message...

like image 263
dhpizza Avatar asked Jun 05 '12 16:06

dhpizza


2 Answers

The hello world example goes only half way and outputs the hard-coded values:

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

Printing the actual response can be done as follows:

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

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

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

There are some other useful examples in zhelpers.hpp.

like image 197
Nikolai Koudelia Avatar answered Oct 19 '22 17:10

Nikolai Koudelia


I found that the following does what I want:

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;

where msglen is of type int and myMessage is const char * tyoe. In this way, the server receives a human readable message. Hope this is not against any zeromq rules...

like image 21
dhpizza Avatar answered Oct 19 '22 17:10

dhpizza