ZMQ message_t.data()清除数据

时间:2015-07-26 10:30:40

标签: c++ zeromq

参考这个问题: Zeromq: How to access tcp message in c++

我设法创建了一个helloworld服务器,可以很容易地打印发送消息的内容,但我的问题是我无法找到一种方法来清除请求变量中的缓冲区。

这就是我的意思:

当我尝试发送请求时:

tuna

由于某种原因,request.data()返回的指针由于某种原因初始化为6个十六进制字符,并且在memcpy结束后发送的消息为:

tuna�

如果我没有输入任何内容,则消息将变为:

�q���

如果输入足够的字符,则字符可以覆盖它。 此外,即使我在循环开始时重新初始化message_t变量,此数据也会保留在变量中。 这意味着,如果我发送Disestablishmentarianism的邮件,然后发送另一条Pro邮件,则生成的邮件为proestablishmentarianism

这是我的参考代码:

    //sender loop
        using namespace std;
zmq::context_t context(1);
zmq::socket_t socket(context, ZMQ_REQ);

int main(){
    socket.connect("tcp://localhost:28641"); //28641 is the set to be standardised for this kind of communication
    string input = "";
    cout << "this is the client for communicating with Thalamus.\nTo start, input the name of the module to be used:";

    while(true){
        std::cout << "Type a config command:" << std::endl;
        getline(cin, input);
        zmq::message_t request(input.size()+1);
        //(char *)request.data() = ' ';
        std::string req = std::string(static_cast<char*>(request.data()), request.size());
        std::cout << req << std::endl;
        //std::cout << input;
        memcpy ((void *) request.data (), input.c_str(), input.size());
        socket.send (request);
        printf("%s\n",(char*)request.data());

        //  Get the reply.
        zmq::message_t reply;
        socket.recv (&reply);
        std::cout << "response:" << std::endl; 
        printf("%s\n",(char *)reply.data());
        //printf("%s", "moo");


    }


    return 0;
}


    //receiver loop
void Config_Interface(){
    //Config_Interaction uses ipc protocols as an interface to controlling and configuring the execution of the program.
    /*
        requirements:
            start stream
            stop stream
            pause/resume
    */
    zmq::context_t config_context(1);
    zmq::socket_t config_socket(config_context, ZMQ_REP);
    config_socket.bind ("tcp://*:28641");


    while(true){
        zmq::message_t request;

        config_socket.recv(&request);
        std::cout << "config update msg received:" << std::endl;
        std::string req = std::string(static_cast<char*>(request.data()), request.size());
        std::cout << req << std::endl;
        //Config_Parse(request.data()); //Function that will parse the command and update the config variables.
        std::cout << "--updated config--";

        zmq::message_t reply(7);
        memcpy ((void *) reply.data (), "got it", 6);
        config_socket.send (reply);
    }
}

修改 我通过使用以下方法找到了解决方法:    snprintf ((char *) request.data (),input.size()+1,"%s", input.c_str() );代替memcpy,但我觉得它仍然没有完全回答为什么记忆没有被清除的问题。也许我错过了C ++的基本功能,但即使经过大量的搜索,我仍然无法找到它。 :(

1 个答案:

答案 0 :(得分:0)

你应该使用

message_t(void* data, size_t len)

//std::string tmp = "example";
//message_t(tmp.c_str(), tmp.size());

初始化