重构Boost ASIO TCP服务器类以便对会话实例进行公共访问

时间:2013-10-04 03:24:43

标签: boost tcp boost-asio

我正在使用Boost ASIO TCP示例,并且有关于访问会话实例(new_session)的问题。基本上,我希望能够计算活动会话实例并在每个会话的handle_write方法中写入不同的数据集。重构服务器类以访问服务器类之外的会话实例的最佳方法是什么?

class session
{
public:
    session(boost::asio::io_service& io_service) 
        : socket_(io_service)
    {
    }

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

    void start()
    {
    std::string message("First message from server\n");
    boost::asio::write(socket, boost::asio::buffer(message));
    }

    void handle_write(const boost::system::error_code& error)
    {
        if (!error)
        {
            std::string message("Hello from server\n");
        boost::asio::write(socket, boost::asio::buffer(message));
        }
        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));
    }

    void handle_accept(session* new_session,
        const boost::system::error_code& error)
    {
        if (!error)
        {
            new_session->start();
            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
        {
            delete new_session;
        }
    }

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

0 个答案:

没有答案