我的代码中有一个问题。
当连接完成时,每个连接都会有 10 兆字节的内存泄漏。
连接工作正常,发送的数据包有效。
我不知道哪里错了。
工人功能:
void worker(boost::shared_ptr<CConnection> connection)
{
boost::asio::ip::tcp::socket &socket = *(connection->socket);
boost::asio::socket_base::non_blocking_io make_non_blocking(true);
socket.io_control(make_non_blocking);
while ( connection->close == false ) {
char * buffer = new char[16]();
buffer[0] = 16;
buffer[4] = 1;
buffer[8] = 1;
buffer[12] = 1;
boost::asio::async_write(socket, boost::asio::buffer(buffer, 16), boost::bind(handle_write, buffer));
connection->close = true;
} // while connection not to be closed
LOG(INFO, "Connection finished!");
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both);
socket.close();
}
接受者代码:
void CCore::handle_accept(const boost::system::error_code& error)
{
if (error) {
// accept failed
LOG(ERROR, "Acceptor failed: " << error.message());
return;
}
LOG(INFO, "Accepted connection from " << this->connection->endpoint.address().to_string() << ":" << this->connection->endpoint.port());
this->connection->thread = boost::shared_ptr<boost::thread>(new boost::thread(worker, this->connection));
this->connection = boost::shared_ptr<CConnection>(new CConnection());
this->connection->master_io_service = this->io_service;
this->acceptor->async_accept(*(this->connection->socket), this->connection->endpoint, boost::bind(&CCore::handle_accept, this, boost::asio::placeholders::error));
}
连接定义:
class CConnection {
public:
CConnection(void);
boost::asio::io_service io_service;
boost::shared_ptr<boost::asio::ip::tcp::socket> socket;
boost::asio::ip::tcp::endpoint endpoint;
boost::shared_ptr<boost::thread> thread;
boost::asio::io_service *master_io_service;
bool close;
};
数据包数据在 handle_write 中被释放:
void handle_write(char * buf)
{
delete [] buf;
}
感谢帮助。