Zeromq:如何访问tcp消息在c ++ [英] Zeromq: How to access tcp message in c++

查看:313
本文介绍了Zeromq:如何访问tcp消息在c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是ZeroMQ的新手,通过echo客户端 - 服务器模式(请求 - 回复)的C ++ hello-world示例。服务器如下:

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



现在我的问题:如何访问/读取套接字的真实数据。 recv()?尝试:

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

 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’

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

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

推荐答案

hello世界的例子只有一半,硬编码值:

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;

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

There are some other useful examples in zhelpers.hpp.

这篇关于Zeromq:如何访问tcp消息在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆