unilink  0.4.3
A simple C++ library for unified async communication
boost_tcp_acceptor.cc
Go to the documentation of this file.
1 /*
2  * Copyright 2025 Jinwoo Sung
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
18 
19 namespace unilink {
20 namespace transport {
21 
22 namespace net = boost::asio;
23 
24 BoostTcpAcceptor::BoostTcpAcceptor(net::io_context& ioc) : acceptor_(ioc) {}
25 
26 void BoostTcpAcceptor::open(const net::ip::tcp& protocol, boost::system::error_code& ec) {
27  acceptor_.open(protocol, ec);
28  if (!ec) {
29  // Set SO_REUSEADDR to allow immediate port reuse after server shutdown
30  // This prevents "Address already in use" errors in tests and quick restarts
31  acceptor_.set_option(net::socket_base::reuse_address(true), ec);
32  }
33 }
34 
35 void BoostTcpAcceptor::bind(const net::ip::tcp::endpoint& endpoint, boost::system::error_code& ec) {
36  acceptor_.bind(endpoint, ec);
37 }
38 
39 void BoostTcpAcceptor::listen(int backlog, boost::system::error_code& ec) { acceptor_.listen(backlog, ec); }
40 
41 bool BoostTcpAcceptor::is_open() const { return acceptor_.is_open(); }
42 
43 void BoostTcpAcceptor::close(boost::system::error_code& ec) { acceptor_.close(ec); }
44 
46  std::function<void(const boost::system::error_code&, net::ip::tcp::socket)> handler) {
47  acceptor_.async_accept(std::move(handler));
48 }
49 
50 } // namespace transport
51 } // namespace unilink