libcluon  0.0.148
TCPServer.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_TCPSERVER_HPP
10 #define CLUON_TCPSERVER_HPP
11 
12 #include "cluon/TCPConnection.hpp"
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 <functional>
27 #include <mutex>
28 #include <string>
29 #include <thread>
30 
31 namespace cluon {
32 
34  private:
35  TCPServer(const TCPServer &) = delete;
36  TCPServer(TCPServer &&) = delete;
37  TCPServer &operator=(const TCPServer &) = delete;
38  TCPServer &operator=(TCPServer &&) = delete;
39 
40  public:
47  TCPServer(uint16_t port, std::function<void(std::string &&from, std::shared_ptr<cluon::TCPConnection> connection)> newConnectionDelegate) noexcept;
48 
49  ~TCPServer() noexcept;
50 
54  bool isRunning() const noexcept;
55 
56  private:
62  void closeSocket(int errorCode) noexcept;
63  void readFromSocket() noexcept;
64 
65  private:
66  mutable std::mutex m_socketMutex{};
67  int32_t m_socket{-1};
68 
69  std::atomic<bool> m_readFromSocketThreadRunning{false};
70  std::thread m_readFromSocketThread{};
71 
72  std::mutex m_newConnectionDelegateMutex{};
73  std::function<void(std::string &&from, std::shared_ptr<cluon::TCPConnection> connection)> m_newConnectionDelegate{};
74 };
75 } // namespace cluon
76 
77 #endif
Definition: TCPServer.hpp:33
Definition: cluon.hpp:65
#define LIBCLUON_API
Definition: cluon.hpp:56