blob: a113e6aac22e3cd43b796f64ff316eb2152627e3 (
plain)
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
101
102
103
104
105
106
107
108
109
110
111
112
113
|
#include "connectionbase.h"
#include <exception>
#include <iostream>
void ConnectionBase::start_recv() {
request_data(4);
}
void ConnectionBase::got_data(uint8_t* data, std::size_t bytes) {
if(pending_size == 0) {
if(bytes != 4) {
error("Deserialization header error.");
}
uint16_t* header = (uint16_t*)data;
pending_type = (Message::Type)header[0];
pending_size = (std::size_t)header[1];
if(pending_size) {
request_data(pending_size);
return;
}
bytes = 0;
}
if(bytes != pending_size) {
std::cout << "Bytes: " << bytes << " Pending size: " << pending_size << std::endl;
error("Deserialization attempted with incomplete data.");
// TODO: Calling got_data() with incomplete data should be allowed.
}
pending_size = 0;
Message::p m;
switch(pending_type) {
case Message::Types::Hello:
m = make_shared<Message::Hello>();
break;
case Message::Types::Login:
m = make_shared<Message::Login>();
break;
case Message::Types::LoginResponse:
m = make_shared<Message::LoginResponse>();
break;
case Message::Types::GameStart:
m = make_shared<Message::GameStart>();
break;
case Message::Types::Ready:
m = make_shared<Message::Ready>();
break;
case Message::Types::RoundStart:
m = make_shared<Message::RoundStart>();
break;
case Message::Types::RoundState:
m = make_shared<Message::RoundState>();
break;
case Message::Types::RoundAction:
m = make_shared<Message::RoundAction>();
break;
case Message::Types::RoundEnd:
m = make_shared<Message::RoundEnd>();
break;
default:
error("Deserialization attempted on unknown message type.");
}
if(bytes) {
try {
m->deserialize(data, bytes);
} catch(std::exception& e) {
error(std::string("Deserialization failed: ") + e.what());
}
}
got_message(m);
}
void ConnectionBase::send(const Message::p& msg) {
uint16_t* header = new uint16_t[2];
std::pair<uint8_t*, std::size_t> smsg = msg->serialize();
header[0] = uint16_t(msg->type);
header[1] = uint16_t(smsg.second);
write_data((uint8_t*)header, 4);
if(smsg.second) {
write_data(smsg.first, smsg.second);
}
}
ConnectionBase::ConnectionBase() {
pending_size = 0;
}
ConnectionBase::~ConnectionBase() {
std::cout << "Connection destroyed." << std::endl;
}
|