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

时间:2013-02-01 15:55:54

标签: c++ boost zeromq boost-serialization

这是我之前在Boost: De-serializing a custom C++ object passed over ZeroMQ pull socket的另一个帖子中打开的后续问题。该线程中的问题已根据提供的答案得到解决。现在我在运行时遇到了另一个问题。请参阅以下说明。我是C ++领域的新手,所以如果你告诉我除了我在问题陈述下所描述的代码之外提供的代码的任何部分,我都感激不尽。

说明

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

序列化和发送任务已在类ZMQHandler (请参阅sendToBE函数)中实现,该函数位于代码段3 中显示的头文件名ZMQHandler.hxx中下面。此类由 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: 

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

   };

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

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

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

1 个答案:

答案 0 :(得分:1)

当我在我的系统上构建并运行代码时,TestBE会抛出反序列化异常(每次)。以下是我为解决这个问题所做的工作:

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

TestFE中,zmqHandler.sendToBE(&msg);变为zmqHandler.sendToBE(msg);

如果theMsg必须是指针

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