我使用了boost :: asio,有8个线程
boost::asio::io_service ios;
boost::asio::ip::tcp::acceptor(ios);
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), port);
acceptor.open(endpoint.protocol());
acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor.listen();
LocalTcpServer::getInstance()->initialize(ios, acceptor, pool);
boost::thread_group th_group;
for(i=0; i< 8; i++)
th_group.add_thread(new boost::thread(boost::bind(&boost::asio::io_service::run, &ios)));
th_group.join_all();
session::start()
{
socket.async_read_some(boost::asio::buffer(buffer), m_strand.wrap(boost::bind(&session::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)))
}
session::handleread(boost::system::error_code &e, size_t byteTrans)
{
if(e || byteTrans == 0 )
{
socket.shutdown(...)
//socketRelease close the socket and delete this
timeInfo->timer->async_wait(boost::bind(socketRelease(), ...);
}
else
{
//deal with data whit pool;
}
socket.async_read_some(.....);
}
LocaltcpServer::initialize(ios, acceptor, pool){
//init, pool is inherit from threadpool, used in handle read to deal with receive data
...;
startaccept();
}
LocalTcpServer::Accept()
{
session* pSession = new session(acceptor->get_io_service, pool);
acceptor.async_accept(session->socket, boost::bind(handle_accept, this, pSession, boost::asio::placeholder::error))
}
LocalTcpServer::handle_accept(boost::system::error_code& e; ... );
{
if(e)
{
//when app run sometime(serveral hours or days, e has always error 22, means invalid argument )
LOG_ERROR << e.message() << e.value();
delete newSession;
accept();
}
else
{
session.start();
accept();
}
}
该应用程序最初工作正常,但有些时候,可能会在几个小时后,1或两天后,错误来了,hander_accpte总是得到一个错误的,无效的参数。所以,没有新的连接,
套接字连接几乎是10000,文件打开限制是65535, 我已经使用netstat检查套接字是否正常关闭,没有套接字whitout关闭 我想知道为什么发生错误,我该如何解决它, 或者如果我的代码有错误? 我希望我能清楚地描述这个问题。感谢。
答案 0 :(得分:0)
如果侦听套接字也出现故障,其中一个主要嫌疑人是dhcp。接口的IP地址可能已更改。
在这种情况下,绑定到该接口的所有打开套接字都将变为无效,必须关闭,包括监听套接字,然后必须使用新套接字重新启动监听。