c++ - 如何将这个 Boost ASIO 示例应用到我的应用程序中

标签 c++ boost boost-asio

我已经阅读了很多 ASIO 示例,但我仍然对如何在我的应用程序中使用它们感到困惑。

基本上,我的服务器端需要接受超过100个连接(客户端),这部分是通过使用线程池(通常每个CPU核心2~4个线程)来完成的。

为简单起见,我们假设只有一个连接。

为简单起见,我还想从以下位置复制示例:http://www.boost.org/doc/libs/1_47_0/doc/html/boost_asio/example/nonblocking/third_party_lib.cpp

class session
{
public:
    session(tcp::socket&)
    bool want_read() const;
    bool do_read(boost::system::error_code&);
    bool want_write() const;
    bool do_write(boost::system::error_code&);
};

class connection : public boost::enable_shared_from_this<connection>
{
public:
    typedef boost::shared_ptr<connection> pointer;
    static pointer create(boost::asio::io_service&);
    tcp::socket& socket();
    void start();
private:
    connection(boost::asio::io_service&);
    void start_operation();
    void handle_read(boost::system::error_code);
    void handle_write(boost::system::error_code);
}

class server
{
public:
    server(boost::asio::io_service&, unsigned short);
private:
    void start_accept();
    void handle_accept(connection::pointer, const boost::system::error_code&);
}

您可以查看完整类实现的链接。

我想做的是将读/写操作添加到类 session 中(或者我应该直接将它们放在 connection 中吗?)

AsyncRead(buffer, expectedBytesToRead, timeout, handler);
Read(buffer, expectedBytesToRead, timeout);
AsyncWrite(buffer, expectedBytesToWrite, timeout, handler);
Write(buffer, expectedBytesToWrite, timeout);

我确实阅读了很多示例,但在我看来很难弄清楚如何使用它们,即在我的应用程序中实现上述 4 个常用方法。

我想我非常接近我想要的,我只是不知道从一个非常简单的例子开始。我阅读@boost.org 的示例,它们要么太复杂而无法弄清逻辑,要么不是我在项目中想要的。

最佳答案

我建议在连接类中保留与套接字的所有通信,使其尽可能通用。

您的选择几乎是无限的。我所做的是将我的“消息处理”类的 shared_ptr 传递给每个新连接,并像您一样创建一个 session ,但我将每个连接的拷贝以及所有相关信息传递给 session 。所以每个单独的 session 可以在收到新消息时通知程序,并且我可以在每个 Session 中存储我想要的任何其他内容。

请注意在连接终止时通知您的 session ,因为您现在将它存储在某个地方,而不仅仅是通过回调使智能指针保持事件状态。

typedef boost::shared_ptr<class Connection> connectionPtr;

void Server::handle_accept(sessionPtr new_connection, const boost::system::error_code& error)
{
if (!error)
{
   cout << "New connection detected." << endl;
   string sessionID = misc::generateSessionID();
   string IPaddress = new_connection->socket().remote_endpoint().address().to_string();
   mSessionManager_->AddSession(new_connection, IPaddress, sessionID);
   // session manager now has a copy of the connection and
   //  can reference this by the sessioNID or IPAddress
   new_connection->start();

   connectionPtr NEWER_CONNECTION(new Connection(_io_service, _loginList, _mMessageHandlerClass));

   cout << "Awaiting next connection..." << endl;
   acceptor_.async_accept(newer_session->socket(),
   boost::bind(&Server::handle_accept, this, NEWER_CONNECTION, 
              boost::asio::placeholders::error));
}
else
{
  new_connection.reset();
}

这里只是一个如何处理消息的例子。显然 totalbytesremaining 需要从 header 中提取,我没有在示例中包含它。

void Session::handle_body(const boost::system::error_code& error, size_t bytes_transferred)
if(!error)
    {
        totalBytesRemaining -= bytes_transferred;

        if (totalBytesRemaining == 0)
            {
            if (incompleteToggle = true)
            {
                tempMessage+=string(readMsg.body());
                messageHandlerClass->Process(sessionID,tempMessage);
                tempMessage = "";
                tempMessageToggle = false;
            }
            else
            {
                tempMessage += string(readMsg.body());
                std::cout << "Incomplete receive:  This is our message So far.\n\n" << tempMessage << "\n" << endl;
                tempMessageToggle = true;
            }

        }

    handle_message();
    }
else
{
    removeSession();
}

所以现在我可以从 SessionManager 类访问我的所有 session

void SessionManager::listConnectedIP()
{
    for (int x = 0; x < sessionBox.size(); x++)
    {
        cout << sessionBox[x]->IPaddress() << endl;
    }
}
void SessionManager::massSendMessage(const std::string &message)
{
    for (int x = 0; x < sessionBox.size(); x++)
    {
        sessionBox[x]->connectionPtr->pushMessage(message);
    }
}

处理消息的Connection类是这样的。消息只是保存缓冲区并对 header 进行编码和解码。这是我在 boost 示例网站上找到的另一个修改类。

void Connection::pushMessage(const string& message)
{
 // boost async_write will return instantly, but guarantees to
 // either error or send all requested bytes.
 // there is no need to check if all bytes get sent in the callback.
    Message writeMsg;
    writeMsg.body_length( strlen(msg.c_str()) );
    memcpy( writeMsg.body(), msg.c_str(), writeMsg.body_length() );
    writeMsg.encode_header();

    boost::asio::async_write(socket_, boost::asio::buffer(writeMsg.data(), writeMsg.length()),
    boost::bind(&Session::handle_write, this, boost::asio::placeholders::error,
    boost::asio::placeholders::bytes_transferred));
}

抱歉,如果我的例子不是很好。要真正掌握 boost::asio 及其示例,您确实需要了解异步函数和回调的工作原理。

关于c++ - 如何将这个 Boost ASIO 示例应用到我的应用程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7235055/

相关文章:

c++ - 避免在 c++ vector 或 valarray 中初始化

c++ - 在 Boost 多索引容器中搜索位域数据

c++ - 为什么这里 `boost::bind()`不能换成 `std::bind()`呢?

c++ - basic_socket_acceptor 接口(interface)在 boost 1.66 中发生了变化……这是一个错误吗?

c++ - vulkan - 计算队列系列 - vkGetDeviceQueue - 访问冲突

c++ - 从函数 C++ 返回文件 ID

c++ - 使用 boost::spirit 将元素解析为 vector ,使用分号或换行符作为分隔符

c++ - 线程安全地关闭同步使用的 boost::asio::ip::tcp::socket

c++ - 为什么 gcc 编译器将版本插入数据部分?

c++ - 为什么 PyGILState_Release 抛出致命的 Python 错误