1//////////////////////////////////////////////////////////////////////
2// This file is part of Remere's Map Editor
3//////////////////////////////////////////////////////////////////////
4// Remere's Map Editor is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Remere's Map Editor is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with this program. If not, see <http://www.gnu.org/licenses/>.
16//////////////////////////////////////////////////////////////////////
17
18#ifndef _RME_NET_CONNECTION_H_
19#define _RME_NET_CONNECTION_H_
20
21#include "position.h"
22
23#include <string>
24#include <vector>
25#include <cstdint>
26#include <thread>
27#include <mutex>
28
29struct NetworkMessage {
30 NetworkMessage();
31
32 void clear();
33 void expand(const size_t length);
34
35 //
36 template <typename T>
37 T read() {
38 // Check if we have enough data left to read
39 if (position + sizeof(T) > buffer.size()) {
40 throw std::runtime_error("Buffer underflow - attempted to read past buffer end");
41 }
42 T& value = *reinterpret_cast<T*>(&buffer[position]);
43 position += sizeof(T);
44 return value;
45 }
46
47 template <typename T>
48 void write(const T& value) {
49 expand(sizeof(T));
50 memcpy(&buffer[position], &value, sizeof(T));
51 position += sizeof(T);
52 }
53
54 //
55 std::vector<uint8_t> buffer;
56 size_t position;
57 size_t size;
58};
59
60template <>
61std::string NetworkMessage::read<std::string>();
62template <>
63Position NetworkMessage::read<Position>();
64template <>
65void NetworkMessage::write<std::string>(const std::string& value);
66template <>
67void NetworkMessage::write<Position>(const Position& value);
68
69class NetworkConnection {
70private:
71 NetworkConnection();
72 NetworkConnection(const NetworkConnection& copy) = delete;
73
74public:
75 ~NetworkConnection();
76
77 static NetworkConnection& getInstance();
78
79 bool start();
80 void stop();
81
82 boost::asio::io_context& get_service();
83
84private:
85 boost::asio::io_context* service;
86 std::thread thread;
87 bool stopped;
88};
89
90#endif
91