gpt4 book ai didi

c++ - 如何通过 boost asio 支持 TCP 服务器中的多个连接

转载 作者:可可西里 更新时间:2023-11-01 02:52:03 25 4
gpt4 key购买 nike

我有以下TCP服务器代码:

#include <algorithm>

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>

#include <iostream>
#include <string>

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

class tcp_connection
: public boost::enable_shared_from_this<tcp_connection>
{
public:
typedef boost::shared_ptr<tcp_connection> pointer;

static pointer create(boost::asio::io_service& io_service)
{
return pointer(new tcp_connection(io_service));
}

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

void start()
{
boost::asio::async_read_until(
_socket
, _message
, "\r\n"
, boost::bind(
&tcp_connection::handle_read
, this->shared_from_this()
, boost::asio::placeholders::error
)
);
}

private:
tcp_connection(boost::asio::io_service& io_service)
: _socket(io_service) {}

void handle_read(const boost::system::error_code& error)
{
if (!error)
{
std::cout << &_message << '\n';
}
}

tcp::socket _socket;
boost::asio::streambuf _message;
};

class tcp_server
{
public:
tcp_server(boost::asio::io_service& io_service)
: _acceptor(io_service, tcp::endpoint(tcp::v4(), 13))
{
start_accept();
}

private:
void start_accept()
{
tcp_connection::pointer new_connection =
tcp_connection::create(_acceptor.get_io_service());

_acceptor.async_accept(
new_connection->socket()
, boost::bind(
&tcp_server::handle_accept
, this
, new_connection
, boost::asio::placeholders::error
)
);
}

void handle_accept(
tcp_connection::pointer new_connection
, const boost::system::error_code& error
)
{
if (!error)
{
new_connection->start();
}

start_accept();
}

tcp::acceptor _acceptor;
};

int main()
{
try
{
boost::asio::io_service io_service;
tcp_server server(io_service);
io_service.run();
}
catch (const std::exception& ex)
{
std::cerr << ex.what() << '\n';
}
}

这段代码不正确支持多个同时连接,因为在我们处理当前消息时 async_accept 没有激活,我说得对吗?我的意思是:

  void handle_accept(
tcp_connection::pointer new_connection
, const boost::system::error_code& error
)
{
// We are unable to accept new connections
if (!error)
{
new_connection->start();
}
// before start_accept function call

start_accept();
}

如果是,我该如何解决这个问题?如何通过支持多连接的 boost asio 编写简约的异步 TCP 服务器?

最佳答案

此代码支持多个同时连接,因为使用的 boost::asio 调用是异步的。 new_connection->start() 立即返回并调用 start_accept()。

关于c++ - 如何通过 boost asio 支持 TCP 服务器中的多个连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22191725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com