如何在 ASIO 中关闭异步客户端连接?

没有

我正在尝试为 C++ 20 服务器示例创建一个客户端,该示例使用协程。

我不太确定我应该如何关闭客户端连接。据我所知,有两种方法:

#1

一旦它准备好,这个似乎正在关闭它/没有其他事情可以像读/写操作那样做。

asio::signal_set signals(io_context, SIGINT, SIGTERM);
signals.async_wait([&](auto, auto) { io_context.stop(); });

#2

强制关闭?

asio::post(io_context_, [this]() { socket_.close(); });

我应该使用哪一种?

客户端代码(未完成)

#include <cstdlib>
#include <deque>
#include <iostream>
#include <thread>
#include <string>

#include <asio.hpp>

using asio::ip::tcp;
using asio::awaitable;
using asio::co_spawn;
using asio::detached;
using asio::redirect_error;
using asio::use_awaitable;

awaitable<void> connect(tcp::socket socket, const tcp::endpoint& endpoint)
{
    co_await socket.async_connect(endpoint, use_awaitable);
}

int main()
{
    try
    {
        asio::io_context io_context;
        tcp::endpoint endpoint(asio::ip::make_address("127.0.0.1"), 666);
        tcp::socket socket(io_context);

        co_spawn(io_context, connect(std::move(socket), endpoint), detached);

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

    return 0;
}

服务器代码

#include <cstdlib>
#include <deque>
#include <iostream>
#include <list>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <asio/awaitable.hpp>
#include <asio/detached.hpp>
#include <asio/co_spawn.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/read_until.hpp>
#include <asio/redirect_error.hpp>
#include <asio/signal_set.hpp>
#include <asio/steady_timer.hpp>
#include <asio/use_awaitable.hpp>
#include <asio/write.hpp>

using asio::ip::tcp;
using asio::awaitable;
using asio::co_spawn;
using asio::detached;
using asio::redirect_error;
using asio::use_awaitable;

//----------------------------------------------------------------------

class chat_participant
{
public:
    virtual ~chat_participant() = default;
    virtual void deliver(const std::string& msg) = 0;
};

typedef std::shared_ptr<chat_participant> chat_participant_ptr;

//----------------------------------------------------------------------

class chat_room
{
public:
    void join(chat_participant_ptr participant)
    {
        participants_.insert(participant);
        for (const auto &msg : recent_msgs_)
            participant->deliver(msg);
    }

    void leave(chat_participant_ptr participant)
    {
        participants_.erase(participant);
    }

    void deliver(const std::string& msg)
    {
        recent_msgs_.push_back(msg);
        while (recent_msgs_.size() > max_recent_msgs)
            recent_msgs_.pop_front();

        for (const auto &participant : participants_)
            participant->deliver(msg);
    }

private:
    std::set<chat_participant_ptr> participants_;
    enum { max_recent_msgs = 100 };
    std::deque<std::string> recent_msgs_;
};

//----------------------------------------------------------------------

class chat_session
    : public chat_participant,
    public std::enable_shared_from_this<chat_session>
{
public:
    chat_session(tcp::socket socket, chat_room& room)
        : socket_(std::move(socket)),
        timer_(socket_.get_executor()),
        room_(room)
    {
        timer_.expires_at(std::chrono::steady_clock::time_point::max());
    }

    void start()
    {
        room_.join(shared_from_this());

        co_spawn(socket_.get_executor(),
            [self = shared_from_this()]{ return self->reader(); },
            detached);

        co_spawn(socket_.get_executor(),
            [self = shared_from_this()]{ return self->writer(); },
            detached);
    }

    void deliver(const std::string& msg) override
    {
        write_msgs_.push_back(msg);
        timer_.cancel_one();
    }

private:
    awaitable<void> reader()
    {
        try
        {
            for (std::string read_msg;;)
            {
                std::size_t n = co_await asio::async_read_until(socket_,
                    asio::dynamic_buffer(read_msg, 1024), "\n", use_awaitable);

                room_.deliver(read_msg.substr(0, n));
                read_msg.erase(0, n);
            }
        }
        catch (std::exception&)
        {
            stop();
        }
    }

    awaitable<void> writer()
    {
        try
        {
            while (socket_.is_open())
            {
                if (write_msgs_.empty())
                {
                    asio::error_code ec;
                    co_await timer_.async_wait(redirect_error(use_awaitable, ec));
                }
                else
                {
                    co_await asio::async_write(socket_,
                        asio::buffer(write_msgs_.front()), use_awaitable);
                    write_msgs_.pop_front();
                }
            }
        }
        catch (std::exception&)
        {
            stop();
        }
    }

    void stop()
    {
        room_.leave(shared_from_this());
        socket_.close();
        timer_.cancel();
    }

    tcp::socket socket_;
    asio::steady_timer timer_;
    chat_room& room_;
    std::deque<std::string> write_msgs_;
};

//----------------------------------------------------------------------

awaitable<void> listener(tcp::acceptor acceptor)
{
    chat_room room;

    for (;;)
    {
        std::make_shared<chat_session>(co_await acceptor.async_accept(use_awaitable), room)->start();
    }
}

//----------------------------------------------------------------------

int main()
{
    try
    {
        unsigned short port = 666;

        asio::io_context io_context(1);

        co_spawn(io_context,
            listener(tcp::acceptor(io_context, { tcp::v4(), port })),
            detached);

        asio::signal_set signals(io_context, SIGINT, SIGTERM);
        signals.async_wait([&](auto, auto) { io_context.stop(); });

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

    return 0;
}
简·加布里埃尔

在由 提供的示例中asiolistenerio_context线程/线程池中运行,run()在构造io_context(1 /* pool of 1 */).

侦听器将使用acceptor来侦听io_context. acceptor会创建一个新的chat_session为每一个新socket的连接,并把它交给了chat_room

因此,要安全地关闭 connection,您需要post一个 lambda to asioasio::post会排队的拉姆达从内进行io_context线程(或多个)。

您需要提供正确io_contextsocketchat_session. 该连接必须从封闭io_context,如下所示:

// Where "this" is the current chat_session owning the socket
asio::post(io_context_, [this]() { socket_.close(); });

所述io_contextWIL然后关闭连接,并且还调用任何活性注册async_read/async_write所述的方法chat_session,如在C ++ 11例如:

void do_read()
  {
    asio::async_read(socket_,
        asio::buffer(read_msg_.data(), chat_message::header_length),
      /* You can provide a lambda to be called on a read / error */
        [this](std::error_code ec, std::size_t /*length read*/)
        {
          if (!ec)
          {
            do_read(); // No error -> Keep on reading
          }
          else
          {
          // You'll reach this point if an active async_read was stopped
          // due to an error or if you called socket_.close()

          // Error -> You can close the socket here as well, 
          // because it is called from within the io_context
            socket_.close(); 
          }
        });
  }

您的第一个选项实际上会停止整个io_context. 这应该用于优雅地退出您的程序或io_context作为一个整体停止 asio

因此,您应该使用第二个选项“关闭 ASIO 中的异步客户端连接”

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何通过Boost Asio制作真正的异步客户端

如何关闭SignalR中的客户端JavaScript“ Hub”连接?

如何关闭WCF客户端连接

asio:服务器如何在同时侦听客户端的同时主动向客户端发送信息?

如何在与客户端连接并行工作的nodejs服务器中创建异步功能?

如何在 uhttpsharp 请求处理程序中关闭客户端连接?

如何在CLion中包含ASIO C ++?

我应该如何在boost :: asio的客户端应用程序中同时使用async_read_until和async_write?

如何在MongoDB中获得连接的客户端

boost :: asio客户端连接停止接收数据

码头如何检测,如果HTTP连接被关闭客户端

如何关闭AWS S3客户端连接

http客户端关闭连接时如何存储响应?

TcpInboundGateway:如何关闭与远程客户端的现有连接

Python 3 asyncio如何正确关闭客户端连接

如何强制关闭客户端连接Rabbitmq

如何增加Boost ASIO,UDP客户端应用程序的吞吐量

boost.asio 如何避免两个客户端在同一个端口连接同一个服务器

如何在boost.asio中打印请求?

如何在UDP的Boost Asio中找到从哪个客户端接收的信息?

服务器如何在服务器/客户端拓扑中检测客户端电源关闭

如何在没有 node.js 的情况下在 js 中建立客户端 - 客户端连接?

如何在Node-Opcua服务器中获得已连接的客户端和客户端证书

如何在 socket.io 中向新客户端显示我连接的客户端?

如何在OpenVPN中与服务器端共享客户端Internet连接?

如何在SignalR客户端中对集线器使用异步/等待

如何在客户端理解异步Meteor.call

如何在C / C ++中关闭特定客户端的套接字?

如何在Mockserver Ruby客户端中关闭登录到控制台的权限