#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向量联系起来,我应该如何以及在哪里声明seriliase方法?
答案 0 :(得分:6)
问题是您尝试序列化vector<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);
}
}
}