fix: asio::ip::tcp::acceptor need call listen()

This commit is contained in:
tqcq
2025-09-09 17:31:11 +08:00
parent ec0f2075d4
commit 10b82da4fd

View File

@@ -20,7 +20,8 @@ initLog()
class RedisServer { class RedisServer {
public: public:
RedisServer(asio::ip::tcp::endpoint ep = asio::ip::tcp::endpoint(asio::ip::tcp::v4(), 6379), int io_thread_num = 2) RedisServer(asio::ip::tcp::endpoint ep = asio::ip::tcp::endpoint(asio::ip::tcp::v4(), 6379), int io_thread_num = 2)
: _io_context(), : _running(false),
_io_context(),
_io_context_guard(asio::make_work_guard(_io_context)), _io_context_guard(asio::make_work_guard(_io_context)),
_io_threads(), _io_threads(),
_acceptor(_io_context, ep) _acceptor(_io_context, ep)
@@ -30,10 +31,13 @@ public:
} }
} }
bool running() const { return true; } ~RedisServer() { _io_threads.join_all(); }
bool running() const { return _running; }
bool startServer() bool startServer()
{ {
_acceptor.listen(1024);
LOGI("Listen {}:{}", _acceptor.local_endpoint().address().to_string(), _acceptor.local_endpoint().port()); LOGI("Listen {}:{}", _acceptor.local_endpoint().address().to_string(), _acceptor.local_endpoint().port());
startAccept(); startAccept();
return true; return true;
@@ -46,6 +50,7 @@ private:
if (!ec) { if (!ec) {
auto remote_ep = new_socket.remote_endpoint(); auto remote_ep = new_socket.remote_endpoint();
LOGI("Connected to Server, From {}:{}", remote_ep.address().to_string(), remote_ep.port()); LOGI("Connected to Server, From {}:{}", remote_ep.address().to_string(), remote_ep.port());
_io_context.stop();
} else { } else {
LOGE("Accept failed. reason={}", ec.message()); LOGE("Accept failed. reason={}", ec.message());
} }
@@ -55,6 +60,7 @@ private:
} }
private: private:
std::atomic<bool> _running;
asio::io_context _io_context; asio::io_context _io_context;
asio::executor_work_guard<asio::io_context::executor_type> _io_context_guard; asio::executor_work_guard<asio::io_context::executor_type> _io_context_guard;
thread_group _io_threads; thread_group _io_threads;