libcluon  0.0.148
TCPConnection.hpp
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2017-2018 Christian Berger
3  *
4  * This Source Code Form is subject to the terms of the Mozilla Public
5  * License, v. 2.0. If a copy of the MPL was not distributed with this
6  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7  */
8 
9 #ifndef CLUON_TCPCONNECTION_HPP
10 #define CLUON_TCPCONNECTION_HPP
11 
13 #include "cluon/cluon.hpp"
14 
15 // clang-format off
16 #ifdef WIN32
17  #include <Winsock2.h> // for WSAStartUp
18  #include <ws2tcpip.h> // for SOCKET
19 #else
20  #include <netinet/in.h>
21 #endif
22 // clang-format on
23 
24 #include <cstdint>
25 #include <atomic>
26 #include <chrono>
27 #include <functional>
28 #include <memory>
29 #include <mutex>
30 #include <string>
31 #include <thread>
32 
33 namespace cluon {
85  private:
86  friend class TCPServer;
87 
93  TCPConnection(const int32_t &socket) noexcept;
94 
95  private:
96  TCPConnection(const TCPConnection &) = delete;
97  TCPConnection(TCPConnection &&) = delete;
98  TCPConnection &operator=(const TCPConnection &) = delete;
99  TCPConnection &operator=(TCPConnection &&) = delete;
100 
101  public:
110  TCPConnection(const std::string &address,
111  uint16_t port,
112  std::function<void(std::string &&, std::chrono::system_clock::time_point &&)> newDataDelegate = nullptr,
113  std::function<void()> connectionLostDelegate = nullptr) noexcept;
114 
115  ~TCPConnection() noexcept;
116 
117  public:
118  void setOnNewData(std::function<void(std::string &&, std::chrono::system_clock::time_point &&)> newDataDelegate) noexcept;
119  void setOnConnectionLost(std::function<void()> connectionLostDelegate) noexcept;
120 
121  public:
125  bool isRunning() const noexcept;
126 
133  std::pair<ssize_t, int32_t> send(std::string &&data) const noexcept;
134 
135  private:
141  void closeSocket(int errorCode) noexcept;
142  void startReadingFromSocket() noexcept;
143  void readFromSocket() noexcept;
144 
145  private:
146  mutable std::mutex m_socketMutex{};
147  int32_t m_socket{-1};
148  bool m_cleanup{true};//if not created from TCPServer,call WSACleanup
149  struct sockaddr_in m_address {};
150 
151  std::atomic<bool> m_readFromSocketThreadRunning{false};
152  std::thread m_readFromSocketThread{};
153 
154  std::mutex m_newDataDelegateMutex{};
155  std::function<void(std::string &&, std::chrono::system_clock::time_point)> m_newDataDelegate{};
156 
157  mutable std::mutex m_connectionLostDelegateMutex{};
158  std::function<void()> m_connectionLostDelegate{};
159 
160  private:
161  class PipelineEntry {
162  public:
163  std::string m_data;
164  std::chrono::system_clock::time_point m_sampleTime;
165  };
166 
167  std::shared_ptr<cluon::NotifyingPipeline<PipelineEntry>> m_pipeline{};
168 };
169 } // namespace cluon
170 
171 #endif
Definition: TCPServer.hpp:33
Definition: cluon.hpp:65
STL namespace.
#define LIBCLUON_API
Definition: cluon.hpp:56
Definition: TCPConnection.hpp:84