boost asio async tcp echo server示例中的内存泄漏

时间:2017-01-30 11:20:20

标签: boost boost-asio

以下代码基于http://www.boost.org/doc/libs/1_46_1/doc/html/boost_asio/example/echo/async_tcp_echo_server.cpp的boost文档示例。我只是稍微更改了一下,以便我可以在不同的线程中运行服务器,并在运行几秒后退出。

此代码按预期工作。当客户端连接并发送一些文本时,副本将回显给客户端。

只有一个问题。有一个类session的实例永远不会被删除。如果运行代码,则可以看到构造函数和析构函数被调用的次数。它始终是最后一个session实例,不会被删除。

想知道是否有一种简单的方法来解决这个问题。也许我可以使用smart_ptr类。

请注意,我必须使用boost库1.46。我发现其他一些例子都是基于较新的库版本。但是这些示例不能在较旧的boost库下编译。问候。

#include <cstdlib>
#include <iostream>
#include <vector>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>

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

class session 
{
public:
  session(boost::asio::io_service& io_service)
    : socket_(io_service)
  {
     char buf[100]; sprintf(buf, "%p", this);
     std::cout << "Session created: " << buf << std::endl;
  }

  ~session() {
     char buf[100]; sprintf(buf, "%p", this);
     std::cout << "Session destroyed: " << buf << std::endl;
  }

  tcp::socket& socket()
  {
    return socket_;
  }

  void start()
  {
    socket_.async_read_some(boost::asio::buffer(data_, max_length),
        boost::bind(&session::handle_read, this,
          boost::asio::placeholders::error,
          boost::asio::placeholders::bytes_transferred));
  }

  void handle_read(const boost::system::error_code& error,
      size_t bytes_transferred)
  {
    if (!error)
    {
      boost::asio::async_write(socket_,
          boost::asio::buffer(data_, bytes_transferred),
          boost::bind(&session::handle_write, this,
            boost::asio::placeholders::error));
    }
    else
    {
      delete this;
    }
  }

  void handle_write(const boost::system::error_code& error)
  {
    if (!error)
    {
      socket_.async_read_some(boost::asio::buffer(data_, max_length),
          boost::bind(&session::handle_read, this,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));
    }
    else
    {
      delete this;
    }
  }

private:
  tcp::socket socket_;
  enum { max_length = 1024 };
  char data_[max_length];
};

class server
{
public:
  server(boost::asio::io_service& io_service, short port)
    : io_service_(io_service),
      acceptor_(io_service, tcp::endpoint(tcp::v4(), port))
  {
    session* new_session =  new session(io_service_);
    acceptor_.async_accept(new_session->socket(),
        boost::bind(&server::handle_accept, this, new_session,
          boost::asio::placeholders::error));
  }

  ~server() {
  }

  void handle_accept(session* new_session,
      const boost::system::error_code& error)
  {
    if (!error)
    {
      new_session->start(); // ownership passed
      new_session = new session(io_service_);
      acceptor_.async_accept(new_session->socket(),
          boost::bind(&server::handle_accept, this, new_session,
            boost::asio::placeholders::error));
    }
    else
    {
      std::cout << "Error in HA: " << error.message() << std::endl;
    }
  }

private:
  boost::asio::io_service& io_service_;
  tcp::acceptor acceptor_;
};

/*
int main(int argc, char* argv[])
{
  try
  {
    if (argc != 2)
    {
      std::cerr << "Usage: async_tcp_echo_server <port>\n";
      return 1;
    }

    boost::asio::io_service io_service;

    using namespace std; // For atoi.
    server s(io_service, atoi(argv[1]));

    io_service.run();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}
*/

static void serverThread(boost::asio::io_service* io_service) {
    server s(*io_service, 5000);
    io_service->run();
}

int main(int argc, char* argv[])
{
    boost::asio::io_service io_service;
    boost::thread t(serverThread, &io_service);

    ::sleep(10);
    io_service.stop();
    t.join();
    std::cout << "Quitting" << std::endl;
    return 0;
}

1 个答案:

答案 0 :(得分:1)

未被删除的那个是传递给异步接受处理程序的那个,即handler_accept。我会建议大量使用智能指针。 shared_ptr在这里是一个很好的候选人:

#include <cstdlib>
#include <iostream>
#include <vector>
#include <thread>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <memory>

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

class session: public std::enable_shared_from_this<session>
{
public:
  session(boost::asio::io_service& io_service)
    : socket_(io_service)
  {
     char buf[100]; sprintf(buf, "%p", this);
     std::cout << "Session created: " << buf << std::endl;
  }

  ~session() {
     char buf[100]; sprintf(buf, "%p", this);
     std::cout << "Session destroyed: " << buf << std::endl;
  }

  tcp::socket& socket()
  {
    return socket_;
  }

  void start()
  {
    socket_.async_read_some(boost::asio::buffer(data_, max_length),
        boost::bind(&session::handle_read, shared_from_this(),
          boost::asio::placeholders::error,
          boost::asio::placeholders::bytes_transferred));
  }

  void handle_read(const boost::system::error_code& error,
      size_t bytes_transferred)
  {
    if (!error)
    {
      boost::asio::async_write(socket_,
          boost::asio::buffer(data_, bytes_transferred),
          boost::bind(&session::handle_write, shared_from_this(),
            boost::asio::placeholders::error));
    }
  }

  void handle_write(const boost::system::error_code& error)
  {
    if (!error)
    {
      socket_.async_read_some(boost::asio::buffer(data_, max_length),
          boost::bind(&session::handle_read, shared_from_this(),
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));
    }
  }

private:
  tcp::socket socket_;
  enum { max_length = 1024 };
  char data_[max_length];
};

using session_ptr = std::shared_ptr<session>;

class server
{
public:
  server(boost::asio::io_service& io_service, short port)
    : io_service_(io_service),
      acceptor_(io_service, tcp::endpoint(tcp::v4(), port))
  {
    auto new_session =  std::make_shared<session>(io_service_);
    acceptor_.async_accept(new_session->socket(),
        boost::bind(&server::handle_accept, this, new_session,
          boost::asio::placeholders::error));
  }

  ~server() {
  }

  void handle_accept(session_ptr new_session,
      const boost::system::error_code& error)
  {
    if (!error)
    {
      new_session->start(); // ownership passed
      new_session.reset();
      new_session = std::make_shared<session>(io_service_);
      acceptor_.async_accept(new_session->socket(),
          boost::bind(&server::handle_accept, this, new_session,
            boost::asio::placeholders::error));
    }
    else
    {
      std::cout << "Error in HA: " << error.message() << std::endl;
    }
  }

private:
  boost::asio::io_service& io_service_;
  tcp::acceptor acceptor_;
};

/*
int main(int argc, char* argv[])
{
  try
  {
    if (argc != 2)
    {
      std::cerr << "Usage: async_tcp_echo_server <port>\n";
      return 1;
    }

    boost::asio::io_service io_service;

    using namespace std; // For atoi.
    server s(io_service, atoi(argv[1]));

    io_service.run();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}
*/

static void serverThread(boost::asio::io_service* io_service) {
    server s(*io_service, 5000);
    io_service->run();
}

int main(int argc, char* argv[])
{
    boost::asio::io_service io_service;
    std::thread t(serverThread, &io_service);

    ::sleep(10);
    io_service.stop();
    t.join();
    std::cout << "Quitting" << std::endl;
    return 0;
}

我使用了c ++ 11功能,即std::threadstd::shared_ptrstd::enable_shared_from_this使您能够创建shared_ptr this对象。在session类的异步函数调用中查看它是如何使用的。

另外,看一下代码,我觉得你打算在调用io_service::stop后调用一些错误代码来处理处理程序?不,事实并非如此。它将简单地调用scheduler::shutdown,它只会破坏异步处理程序,而不是别的。