但是,当我收到一次数据时,连接已关闭.我不明白为什么.
我认为我应该制作一个循环,但我们告诉我这不是一个好主意.
class clIEnt{public: clIEnt(boost::asio::io_service& io_service,const std::string& host,const std::string& service) : connection_(io_service) { // Resolve the host name into an IP address. boost::asio::ip::tcp::resolver resolver(io_service); boost::asio::ip::tcp::resolver::query query(host,service); boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); boost::asio::ip::tcp::endpoint endpoint = *endpoint_iterator; // Start an asynchronous connect operation. connection_.socket().async_connect(endpoint,boost::bind(&clIEnt::handle_connect,this,boost::asio::placeholders::error,++endpoint_iterator)); } /// Handle completion of a connect operation. voID handle_connect(const boost::system::error_code& e,boost::asio::ip::tcp::resolver::iterator endpoint_iterator) { if (!e) { // Successfully established connection. Start operation to read the List // of stocks. The connection::async_read() function will automatically // decode the data that is read from the underlying socket. connection_.async_read(stocks_,boost::bind(&clIEnt::handle_read,boost::asio::placeholders::error)); } else { std::cerr << e.message() << std::endl; } } /// Handle completion of a read operation. voID handle_read(const boost::system::error_code& e) { if (!e) { // Print out the data that was received. for (std::size_t i = 0; i < stocks_.size(); ++i) { std::cout << "Paquet numero " << i << "\n"; std::cout << " age: " << stocks_[i].age << "\n"; std::cout << " name: " << stocks_[i].nom << "\n"; } // Maybe Should i put something here ? } else { // An error occurred. std::cerr << "Error : " << e.message() << std::endl; connection_.socket().close(); } // or maybe here ? }private: /// The connection to the server. connection connection_; std::vector<stock> stocks_;};
主要看起来像这样:
int main(int argc,char* argv[]){ try { // Check command line arguments. if (argc != 3) { std::cerr << "Usage: clIEnt <host> <port>" << std::endl; return 1; } boost::asio::io_service io_service; clIEnt clIEnt(io_service,argv[1],argv[2]); io_service.run(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0;}解决方法 首先,您的asio io_service正在完成工作.在handle_read中,你把评论“也许我应该把东西放在这里”你可以安排下一个异步读 *** 作:
connection_.async_read(stocks_,boost::asio::placeholders::error));
通常情况下,如果您是异步编程,一旦是异步编程.调用handler,你将调用下一个异步. *** 作,就像你在异步连接处理程序中所做的那样.
@H_301_40@ 总结以上是内存溢出为你收集整理的提升asio:如何保持客户端连接活着?全部内容,希望文章能够帮你解决提升asio:如何保持客户端连接活着?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)