1
#include<iostream>
#include<boost/thread.hpp> 
#include<vector>
#include<boost/asio.hpp> 
#include <ctime>
#include <string>
#include <boost/serialization/vector.hpp>
#include <boost/archive/text_oarchive.hpp> 
#include <sstream> 

using boost::asio::ip::tcp;

std::string make_daytime_string()
{
    using namespace std; // For time_t, time and ctime;
    time_t now = time(0);
    return ctime(&now);
}

class maintain_overlay{

public:
    maintain_overlay():thread_(boost::bind(&maintain_overlay::member_list_server, this))    
    {
        thread_.join();
    }
    void member_list_server(){
        boost::asio::io_service io_service;

        tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 13));

        for (;;)
        {
            tcp::socket socket(io_service);
            acceptor.accept(socket);

            member_list.push_back(socket.remote_endpoint());

            std::string message = make_daytime_string();

            std::stringstream ss; 
            boost::archive::text_oarchive oa(ss); 
            oa<<member_list;/////////////error comes because of this code

            boost::system::error_code ignored_error;
            boost::asio::write(socket, boost::asio::buffer(message),
                boost::asio::transfer_all(), ignored_error);


        }
    }

private:
    std::vector<tcp::endpoint> member_list;
    boost::thread thread_;
    friend class boost::serialization::access;  
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & member_list;
    }



};

我得到错误

error C2039: 'serialize' : is not a member of 'boost::asio::ip::basic_endpoint<InternetProtocol>'

- - 编辑 - - -

我认为我犯的一个错误是我试图序列化成员数据而不是整个对象实例......如果我想序列化 meber_list 向量,我应该如何以及在哪里声明序列化方法?

4

1 回答 1

7

问题是您正在尝试序列化 avector<tcp::endpoint>tcp::endpoint不可序列化。

如果您只想发送连接的 IP 地址和端口,则必须从 中提取它们tcp::endpoint或编写您自己的序列化/反序列化方法。

您可以像这样以非侵入性方式重载 boost 的序列化函数:

namespace boost {
namespace serialization {

template<class Archive, class Protocol>
void save(Archive & ar, asio::ip::basic_endpoint<Protocol> & e, unsigned int version)
{
    string ip = e.address().to_string();
    short port = e.port();
    ar & ip;
    ar & port;
}
template<class Archive, class Protocol>
void load(Archive & ar, asio::ip::basic_endpoint<Protocol> & e, unsigned int version)
{
    string ip;
    short port;
    ar & ip;
    ar & port;
    e = asio::ip::basic_endpoint<Protocol>(ip, port);

}

template<class Archive, class Protocol>
inline void serialize(Archive & ar, asio::ip::basic_endpoint<Protocol> & e, const unsigned int file_version) {
    split_free(ar, e, file_version); 
}

}
}
于 2013-05-23T12:13:42.390 回答