-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathecho_server.cpp
101 lines (84 loc) · 2.72 KB
/
echo_server.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <sstream>
#include <string>
#include <cereal/types/deque.hpp>
#include "cereal/archives/portable_binary.hpp"
#include "Util.hpp"
#include "Force.hpp"
#include "Archiver.hpp"
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#define ASIO_STANDALONE
#include "asio.hpp"
#include <unistd.h>
#include <vector>
class Receiver {
private:
io_service& io;
unsigned short port;
udp_socket socket;
std::stringstream read(int reply_size) {
std::vector<char> reply(reply_size);
udp_endpoint sender_endpoint;
int reply_length = socket.receive_from(
asio::buffer(reply.data(), reply_size), sender_endpoint);
auto addr = sender_endpoint.address();
auto port = sender_endpoint.port();
std::cout << addr << ":" << port << "\n";
std::stringstream ss; // any stream can be used
ss.write(reply.data(), reply_length); // reply data to stream
return ss;
}
public:
Receiver(io_service& io, unsigned short port) :
io(io),
port(port),
socket(io, udp_endpoint(asio::ip::udp::v4(), port))
{
}
bool available() {
return socket.available() > 0;
}
template <typename Serializable_Items>
Serializable_Items static deserialize(std::stringstream& ss) {
Serializable_Items items;
{
cereal::PortableBinaryInputArchive iarchive(ss); // Create an input archive
iarchive(items); // Read the data from the archive
} // flush
return items;
}
template <typename Serializable_Items>
Serializable_Items receive() {
Serializable_Items items;
int reply_size = socket.available();
//std::deque<Serializable> items;
if (reply_size > 0) {
std::stringstream ss = read(reply_size);
items = deserialize<Serializable_Items>(ss);
} else {
;
}
return items;
}
};
int main(int argc, char* argv[]) {
io_service io;
Receiver receiver(io,2000);
usleep(5 * 1000 * 1000);
while (1) {
if (receiver.available()) {
Forces fs;
fs = receiver.receive<Forces>();
std::cout << "Server received:\n";
for (const auto& f: fs) {
std::cout << "Server reads " << f.id << "\n";
}
std::cout << "Server receive end\n";
}
}
return 0;
}