跟进:Boost序列化自定义C++对象通过ZeroMQ pull socket传递

F. *_*mir 5 c++ boost zeromq boost-serialization

这是我之前在Boost的另一个线程中打开的一个后续问题:反序列化通过ZeroMQ pull socket传递的自定义C++对象.该线程中的问题已根据提供的答案得到解决.现在我在运行时遇到了另一个问题.请参阅以下说明.我是C++领域的新手,所以如果你告诉我除了我在问题陈述下所描述的代码之外提供的代码的任何部分,我还要感谢.

描述:

我有一个名为GenericMessage的C++类,它只包含一个id和data作为其成员(参见下面的代码片段2 - GenericMessage.hxx).我的目的是序列化这个类的一个实例,并通过一个实现推送模式的ZeroMQ套接字发送它.

序列化和发送任务已在ZMQHandler类中实现(请参阅sendToBE函数),该函数放在头文件名ZMQHandler.hxx中,如下面的代码片段3所示.此类由TestFE.cxx实例化,如下面的第4个代码片段所示.

GenericMessage实例的接收和反序列化在TestBE.cxx 中实现,可在下面的第5个代码片段中找到.我的目的是通过ZMQ套接字(即拉套接字)接收GenericMessage实例,对其进行反序列化,然后将其成员打印到标准输出.

我验证了通过ZeroMQ套接字传输的seriazalition和GenericMessage对象可以正常工作.反序列化似乎也起作用,因为我没有得到任何异常或分段错误之类的东西.

问题陈述:

TestBE.cxx中的代码(参见代码片段5)所期望的是通过ZeroMQ套接字接收GenericMessage对象反序列化它,然后打印它的两个成员,即id和数据,在这种情况下是一个字符串对象.更确切地说,它应首先打印它获取的char流的内容,然后打印反序列化对象的成员.相反,它根本不打印这些成员.Al,它将包括问号在内的奇怪符号放入收到的char流中.请参阅下面的第一个代码段,你会看到我的观点.

问题:

i)为什么我不能得到预期的输出?为什么我在输出中看到标记为奇怪符号的问题?为什么我看不到打印的id和数据字段,尽管它们在打印的字符流中可见?

ii) GenericMessage类中的数据字段是一种模板类型,为了测试目的,它被设置为std :: string.但是,在实际使用中,我计划以序列化形式传输更复杂的对象.在这方面,你认为使用类boost :: archive :: text_iarchive和boost :: archive :: text_oarchive是有用的.我应该使用二进制代码吗?如果是这样,你认为我应该注意一些陷阱/可能存在的问题吗?提前致谢.

SNIPPET 1:程序输出与预期输出

  *******************
  The EXPECTED OUTPUT
  *******************
  Connecting to FE...
  CHAR [22 serialization::archive 9 0 1 0
  0 1 12 Hello there!]
  ID: 1
  Data: Hello there!

  CHAR [22 serialization::archive 9 0 1 0
  0 2 12 Hello there!]
  ID: 2
  Data: Hello there!

  CHAR [22 serialization::archive 9 0 1 0
  0 3 12 Hello there!]
  ID: 3
  Data: Hello there!

  ......


  *************************
  PRINTED OUTPUT IN REALITY
  *************************
  Connecting to FE...
  CHAR [22 serialization::archive 9 0 1 0
  0 1 12 Hello there!]
  ID: 1
  Data: Hello there!

  //continues in increasing order same as above until the 18th message in the following
  CHAR [22 serialization::archive 9 0 1 0
  0 18 12 Hello there!]
  ID: 0
  Data: 

  //!!!!AFTER the 18th message I got question marks in the printed char stream!!!!!
  CHAR [22 serialization::archive 9 0 1 0
  0 19 12 Hello there!???]
  ID: 0
  Data: 

  CHAR [22 serialization::archive 9 0 1 0
  0 20 12 Hello there!???]
  ID: 0
  Data: 
Run Code Online (Sandbox Code Playgroud)

代码SNIPPET 2(GenericMessage.hxx)

  #include <iostream>
  #include <string>
  #include <sstream>
  #include <boost/serialization/serialization.hpp>
  #include <boost/archive/binary_oarchive.hpp>
  #include <boost/archive/binary_iarchive.hpp>
  #include <boost/archive/text_oarchive.hpp>
  #include <boost/archive/text_iarchive.hpp>

  template <class T>
  class GenericMessage {
  public:
    GenericMessage(): 
      beId(-1)
    {}

    GenericMessage(int id, T msg): 
       beId(id), 
       data(msg)
    {}

    ~GenericMessage(){}

    T getData()
    {
      return data;
    }


    std::string toString()
    {
       std::ostringstream ss;
       ss << getBeId();
       std::string ret =  ss.str();

      return ("ID: " + ret + " DATA: " + getData());
    }

    void setBeId(int id)
    {
      beId = id;
    }

    int getBeId()
    {
      return beId;
    }


  private:
    friend class boost::serialization::access;

    int beId;
    T data;


    template <class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & beId;
        ar & data;
    }

   };
Run Code Online (Sandbox Code Playgroud)

代码SNIPPET 3(ZmqHandler.hxx)

   #include "zmq.hpp"
   #include "GenericMessage.hxx"
   #include <unistd.h>
   #include <cassert>

   template <class A>
   class ZmqHandler {
      public:

         ZmqHandler():
     mContext(1),
     mOutbHandlerSocket(mContext, ZMQ_PUSH)
         {    
             mOutbHandlerSocket.bind ("tcp://*:5555");       
         }


         ~ZmqHandler() {}

         void sendToBE(GenericMessage<A> *theMsg)
         {
            std::ostringstream archive_stream;
            boost::archive::text_oarchive archive(archive_stream);

            try
            {
                archive << theMsg;
            } catch (boost::archive::archive_exception& ex) {
                std::cout << "Archive Exception during deserializing:" << std::endl;
                std::cout << ex.what() << std::endl;           
            } catch (int e) {
                std::cout << "EXCEPTION " << e << std::endl; 
            }

           std::string outbound_data_ = archive_stream.str();
           // no need to use the c-style string function 'strlen'
           int len = outbound_data_.length();

           zmq::message_t msgToSend(len);
           memcpy( msgToSend.data(), outbound_data_.data(), len );

           mOutbHandlerSocket.send(msgToSend);
           std::cout << "SENT request: [" << theMsg->toString() << "]" << std::endl;
           std::cout << "LENGTH [" << len << "]" << std::endl;
         }   

        private:  
          zmq::context_t mContext;
          zmq::socket_t mOutbHandlerSocket;         
     };
Run Code Online (Sandbox Code Playgroud)

CODE SNIPPET 4(TestFE.cxx)

       #include "ZmqHandler.hxx"

       int main ()
       {
            ZmqHandler<std::string> zmqHandler;
            int counter = 1;

            while(1)
            {  
                std::string data = "Hello there!";
                GenericMessage<std::string> msg(counter, data);
                zmqHandler.sendToBE(&msg);
                counter++;
                sleep(1);
             }

             return 0;
        }
Run Code Online (Sandbox Code Playgroud)

代码SNIPPET 5(TestBE.cxx)

       #include "zmq.hpp"
       #include "GenericMessage.hxx"
       #include <fstream>

       int main ()
       {
          //  Prepare our context and socket
          zmq::context_t context (1);
          zmq::socket_t socket (context, ZMQ_PULL);

         std::cout << "Connecting to FE..." << std::endl;
         socket.connect ("tcp://localhost:5555");

         while(1){
              zmq::message_t reply;
              socket.recv (&reply);

              const char *buf = static_cast<const char*>(reply.data());
              std::cout << "CHAR [" << buf << "]" << std::endl;

              std::string input_data_( buf, reply.size() ); 
              std::istringstream archive_stream(input_data_);
              boost::archive::text_iarchive archive(archive_stream);
              GenericMessage<std::string> theMsg;

              try
              {
                 archive >> theMsg;
              } catch (boost::archive::archive_exception& ex) {
                 std::cout << "Archive Exception during deserializing:" << std::endl;
                 std::cout << ex.what() << std::endl;           
              } catch (int e) {
                 std::cout << "EXCEPTION " << e << std::endl; 
              }

              std::cout << "ID: " << theMsg.getBeId() << std::endl;
              std::cout << "Data: " << theMsg.getData() << std::endl;

           }

            return 0;
         }
Run Code Online (Sandbox Code Playgroud)

Jac*_*ins 1

当我在我的系统上构建并运行您的代码时,TestBE确实会抛出反序列化异常(每次)。这是我修复它的方法:

在您的ZmqHandler班级中,将方法更改void sendToBE(GenericMessage<A> *theMsg)void sendToBE(GenericMessage<A> theMsg). 如果需要,您可以使用 a const&,但您可能不想在此处使用指针。在同样的方法中,您需要更改theMsg->XXXtheMsg.XXX,因为theMsg不再是指针。

在 中TestFEzmqHandler.sendToBE(&msg);变为zmqHandler.sendToBE(msg);

如果theMsg必须是一个指针

在 中ZmqHandler,只需将行更改archive << theMsgarchive << *theMsg。这样,存档operator<<正在处理对象,而不是指向对象的指针。其余代码可以保持不变。