/* * ===================================================================================== * * Filename: tcp_server.cpp * * Description: * * Version: 1.0 * Created: 2021年05月19日 15时05分33秒 * Revision: none * Compiler: gcc * * Author: Li Chao (), lichao@aiotlink.com * Organization: * * ===================================================================================== */ #include "tcp_server.h" #include "log.h" #include "tcp_connection.h" #include using namespace std::chrono_literals; TcpServer::TcpServer(int port) : run_(false), listener_(io_, tcp::endpoint(tcp::v6(), port)) { Accept(); } TcpServer::~TcpServer() { Stop(); } bool TcpServer::Start() { Stop(); bool cur = false; if (run_.compare_exchange_strong(cur, true)) { auto proc = [this]() { while (run_) { io_.run_one_for(100ms); } }; std::thread(proc).swap(worker_); } } void TcpServer::Stop() { bool cur = true; if (run_.compare_exchange_strong(cur, false)) { io_.post([this]() { listener_.close(); }); std::this_thread::sleep_for(1s); if (worker_.joinable()) { worker_.join(); } } } void TcpServer::Accept() { listener_.async_accept([this](bserror_t ec, tcp::socket sock) { if (!ec) { LOG_INFO() << "server accept client"; TcpReply1::Create(std::move(sock)); } Accept(); }); }