| 37 | TCPServerImpl::~TCPServerImpl() = default; |
| 38 | |
| 39 | Result<Void> TCPServerImpl::start() { |
| 40 | std::lock_guard<Mutex> guard(_mutex); |
| 41 | |
| 42 | if (_asioThread != nullptr) { |
| 43 | return Void(); |
| 44 | } |
| 45 | |
| 46 | boost::system::error_code ec; |
| 47 | _acceptor.open(boost::asio::ip::tcp::v4(), ec); |
| 48 | if (ec.failed()) { |
| 49 | return errorFromBoostError(ec); |
| 50 | } |
| 51 | |
| 52 | _acceptor.set_option(boost::asio::socket_base::reuse_address(true), ec); |
| 53 | if (ec.failed()) { |
| 54 | return errorFromBoostError(ec); |
| 55 | } |
| 56 | |
| 57 | _acceptor.bind({boost::asio::ip::tcp::v4(), static_cast<unsigned short>(_port)}, ec); |
| 58 | if (ec.failed()) { |
| 59 | return errorFromBoostError(ec); |
| 60 | } |
| 61 | |
| 62 | _acceptor.listen(boost::asio::socket_base::max_listen_connections, ec); |
| 63 | if (ec.failed()) { |
| 64 | return errorFromBoostError(ec); |
| 65 | } |
| 66 | |
| 67 | _started = true; |
| 68 | // Allow io_service to be reused after a previous stop() |
| 69 | _ioService.reset(); |
| 70 | // Use a work guard to keep run() active until handler returns to |
| 71 | // prevent possible deadlock if asio thread exits (eg. error or other thread closure) |
| 72 | // and we post and wait indefinitely for the non-existent thread to complete. |
| 73 | _work = std::make_shared<boost::asio::io_service::work>(_ioService); |
| 74 | |
| 75 | auto threadResult = |
| 76 | Thread::create(STRING_LITERAL("Valdi TCP Server"), ThreadQoSClassNormal, [this]() { runIOService(); }); |
| 77 | if (!threadResult) { |
| 78 | _work.reset(); |
| 79 | return threadResult.moveError(); |
| 80 | } |
| 81 | _asioThread = threadResult.moveValue(); |
| 82 | |
| 83 | return Void(); |
| 84 | } |
| 85 | |
| 86 | void TCPServerImpl::runIOService() { |
| 87 | listenNext(); |