这是我在前面的另一个线程Boost: De-serializing a custom C++ object passed over ZeroMQ pull socket中打开的跟进问题。根据提供的答案,该线程中的问题已解决。现在,我在运行时遇到了另一个问题。请参阅以下说明。我实际上是C++领域的新手,因此,如果您告诉我除问题陈述所描述的内容之外,还需要改进所提供代码的任何部分,我将不胜感激。

说明:

我有一个名为 GenericMessage 的C++类,它仅将ID和数据作为其成员(请参见下面的代码段2-GenericMessage.hxx)。我的意图是序列化此类的实例,并通过实现推模式的ZeroMQ套接字发送它。

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

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

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

问题陈述:

TestBE.cxx中的代码(请参见代码段5)所期望的是通过ZeroMQ套接字反序列化接收GenericMessage对象,然后打印其两个成员,即id和data(在这种情况下为字符串对象)。更准确地说,它应该首先打印它获取的char流的内容,然后打印反序列化对象的成员。而是,它根本不打印这些成员。 Al,它将包含问号的怪异符号放入接收到的char流中。请参阅下面的第一个代码段,您将明白我的意思。

问题:

i)为什么我无法获得预期的输出?为什么在输出中看到标记为怪异符号的问题?为什么我看不到id和data字段,尽管它们在已打印的char流中是可见的?

ii) GenericMessage类中的data字段是模板类型,出于测试目的,该模板类型设置为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:

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

   };

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

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

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

最佳答案

当我在系统上构建并运行您的代码时,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<<就可以处理该对象,而不是指向该对象的指针。您的其余代码可以保持不变。

关于c++ - 跟进: Boost serialized custom C++ object passed over ZeroMQ pull socket,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14650104/

10-11 15:32