unilink  0.4.3
A simple C++ library for unified async communication
tcp_client.hpp
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 
17 #pragma once
18 
19 #include <chrono>
20 #include <functional>
21 #include <future>
22 #include <memory>
23 #include <string>
24 #include <string_view>
25 
28 
29 namespace boost {
30 namespace asio {
31 class io_context;
32 }
33 } // namespace boost
34 
35 namespace unilink {
36 
37 namespace interface {
38 class Channel;
39 }
40 
41 namespace wrapper {
42 
47  public:
48  TcpClient(const std::string& host, uint16_t port);
49  TcpClient(const std::string& host, uint16_t port, std::shared_ptr<boost::asio::io_context> external_ioc);
50  explicit TcpClient(std::shared_ptr<interface::Channel> channel);
51  ~TcpClient() override;
52 
53  // Move semantics
54  TcpClient(TcpClient&&) noexcept;
55  TcpClient& operator=(TcpClient&&) noexcept;
56 
57  // Disable copy
58  TcpClient(const TcpClient&) = delete;
59  TcpClient& operator=(const TcpClient&) = delete;
60 
61  // ChannelInterface implementation
62  std::future<bool> start() override;
63  void stop() override;
64  void send(std::string_view data) override;
65  void send_line(std::string_view line) override;
66  bool is_connected() const override;
67 
68  ChannelInterface& on_data(MessageHandler handler) override;
69  ChannelInterface& on_connect(ConnectionHandler handler) override;
70  ChannelInterface& on_disconnect(ConnectionHandler handler) override;
71  ChannelInterface& on_error(ErrorHandler handler) override;
72 
73  ChannelInterface& auto_manage(bool manage = true) override;
74 
75  // Configuration
76  TcpClient& set_retry_interval(std::chrono::milliseconds interval);
77  TcpClient& set_max_retries(int max_retries);
78  TcpClient& set_connection_timeout(std::chrono::milliseconds timeout);
79  TcpClient& set_manage_external_context(bool manage);
80 
81  private:
82  struct Impl;
83  const Impl* get_impl() const { return impl_.get(); }
84  Impl* get_impl() { return impl_.get(); }
85  std::unique_ptr<Impl> impl_;
86 };
87 
88 } // namespace wrapper
89 } // namespace unilink
Definition: serial.hpp:27
#define UNILINK_API
Definition: visibility.hpp:37