unilink  0.4.3
A simple C++ library for unified async communication
udp_builder.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 #include <boost/asio/io_context.hpp>
20 
22 
23 namespace unilink {
24 namespace builder {
25 
26 UdpBuilder::UdpBuilder() : auto_manage_(false), use_independent_context_(false) {
27  // Ensure background IO service is running
29 }
30 
31 std::unique_ptr<wrapper::Udp> UdpBuilder::build() {
32  std::unique_ptr<wrapper::Udp> udp;
33  if (use_independent_context_) {
34  udp = std::make_unique<wrapper::Udp>(cfg_, std::make_shared<boost::asio::io_context>());
35  udp->set_manage_external_context(true);
36  } else {
37  udp = std::make_unique<wrapper::Udp>(cfg_);
38  }
39 
40  if (on_data_) udp->on_data(on_data_);
41  if (on_connect_) udp->on_connect(on_connect_);
42  if (on_disconnect_) udp->on_disconnect(on_disconnect_);
43  if (on_error_) udp->on_error(on_error_);
44 
45  if (auto_manage_) {
46  udp->auto_manage(true);
47  }
48 
49  return udp;
50 }
51 
52 UdpBuilder& UdpBuilder::auto_manage(bool auto_manage) {
53  auto_manage_ = auto_manage;
54  return *this;
55 }
56 
57 UdpBuilder& UdpBuilder::on_data(std::function<void(const wrapper::MessageContext&)> handler) {
58  on_data_ = std::move(handler);
59  return *this;
60 }
61 
62 UdpBuilder& UdpBuilder::on_connect(std::function<void(const wrapper::ConnectionContext&)> handler) {
63  on_connect_ = std::move(handler);
64  return *this;
65 }
66 
67 UdpBuilder& UdpBuilder::on_disconnect(std::function<void(const wrapper::ConnectionContext&)> handler) {
68  on_disconnect_ = std::move(handler);
69  return *this;
70 }
71 
72 UdpBuilder& UdpBuilder::on_error(std::function<void(const wrapper::ErrorContext&)> handler) {
73  on_error_ = std::move(handler);
74  return *this;
75 }
76 
78  cfg_.local_port = port;
79  return *this;
80 }
81 
82 UdpBuilder& UdpBuilder::set_remote(const std::string& address, uint16_t port) {
83  cfg_.remote_address = address;
84  cfg_.remote_port = port;
85  return *this;
86 }
87 
89  use_independent_context_ = use_independent;
90  return *this;
91 }
92 
93 } // namespace builder
94 } // namespace unilink