-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.cpp
335 lines (278 loc) · 9.58 KB
/
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include "util/ts_queue.cpp"
#include "parsing/serverParse.h"
#include "Game.h"
#include "main.h"
#include <glm/gtx/string_cast.hpp>
#define MAX_CONNECTIONS 4
#define PERIOD 17 //server period in ms
#define DELAY_PERIOD 500
using namespace boost::asio;
using ip::tcp;
using std::cout;
using std::endl;
class con_handler : public boost::enable_shared_from_this<con_handler>
{
private:
tcp::socket sock;
std::string message = "Hello From Server!";
enum { max_length = 1024 };
string buffer;
boost::asio::dynamic_string_buffer<char, std::char_traits<char>, std::allocator<char>>
input_buf = boost::asio::dynamic_buffer(buffer);
ThreadSafeQueue<std::string> input_buffer;
public:
int pid;
string pid_str; //for parser
Game* game;
typedef boost::shared_ptr<con_handler> pointer;
con_handler(boost::asio::io_service& io_service, int pid, std::string pid_str, Game* gm) : sock(io_service), pid(pid), pid_str(pid_str) {
game = gm;
}
// creating the pointer
static pointer create(boost::asio::io_service& io_service, int pid, Game* gm)
{
return pointer(new con_handler(io_service, pid, to_string(pid), gm));
}
//socket creation
tcp::socket& socket()
{
return sock;
}
/*
* Start the async read loop of the server
*/
void start()
{
async_read_until(
sock,
input_buf,
"\r\n",
boost::bind(&con_handler::handle_read,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
/*
* Read handler which will push incoming messages onto the input queue
*/
void handle_read(const boost::system::error_code& err, size_t bytes_transferred)
{
if (!err) {
//std::string incoming;
//incoming.assign(data, bytes_transferred);
string temp = buffer.substr(0, buffer.find("\r\n"));
input_buffer.push(temp);
input_buf.consume(bytes_transferred);
async_read_until(
sock,
input_buf,
"\r\n",
boost::bind(&con_handler::handle_read,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
else {
//std::cerr << "error: " << err.message() << std::endl;
sock.close();
}
}
/*
* Simple handler to terminate connection upon error
*/
void handle_send_state(const boost::system::error_code& err, size_t bytes_transferred)
{
if (err) {
//std::cerr << "error: " << err.message() << endl;
sock.close();
}
}
/*
* Join handler which will begin listening for incoming messages from a player
* once it is confirmed that they have received the join_response
*/
void handle_send_join(const boost::system::error_code& err, size_t bytes_transferred)
{
if (!err) {
serverParse::joinMessageHandler();
start();
} else {
//std::cerr << "error: " << err.message() << endl;
sock.close();
}
}
/*
* Method to send the state of the game to the player at the other end of this connection
*/
void send_game_state(std::string state_string)
{
sock.async_write_some(
boost::asio::buffer(state_string, state_string.size()),
boost::bind(&con_handler::handle_send_state,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
/*
* Method to send join_response to the player at the other end of this connection
*/
void send_join_message(){
std::string join_msg = serverParse::buildJoinResponse(to_string(serverParse::userIdCount-1));
sock.async_write_some(
boost::asio::buffer(join_msg, join_msg.size()),
boost::bind(&con_handler::handle_send_join,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
/*
* Method which pops the first message from this connections input buffer
*/
std::string dequeue(){
return input_buffer.pop();
}
};
class Server
{
private:
boost::asio::io_service & io_service_;
tcp::acceptor acceptor_;
con_handler::pointer playerConnections[MAX_CONNECTIONS];
void start_accept()
{
// socket
con_handler::pointer connection = con_handler::create(io_service_, serverParse::userIdCount, game);
// asynchronous accept operation and wait for a new connection.
acceptor_.async_accept(connection->socket(),
boost::bind(&Server::handle_accept, this, connection,
boost::asio::placeholders::error));
}
public:
Game* game;
//constructor for accepting connection from client
Server(boost::asio::io_service& io_service, int portNum) : io_service_(io_service),
acceptor_(io_service_, tcp::endpoint(tcp::v4(), portNum)) {
start_accept();
game = new Game(false);
}
void begin_game()
{
game->beginGame();
game->initiateGame();
std::this_thread::sleep_for(std::chrono::milliseconds(DELAY_PERIOD));
string message = serverParse::createMazeString(game->maze);
while (message.size() > 256) {
for (int j = 255; j >= 0; j--) {
if (message.at(j) == 'm') {
string temp = message.substr(0, j);
//cerr << "sending temp message: " << temp << endl;
//cerr << "temp message size: " << temp.size() << endl;
temp = temp + "\r\n";
broadcast(temp);
message.erase(message.begin(), message.begin() + j);
//cerr << "message size is now: " << message.size() << endl;
break;
}
}
}
if (message.size() > 0) {
message = message + "\r\n";
//cerr << "sending remaining: " << message.size() << endl;
broadcast(message);
}
//broadcast("mU,1,1,1,");
message = "";
std::this_thread::sleep_for(std::chrono::milliseconds(DELAY_PERIOD));
message = serverParse::createAbilityString(game->maze);
broadcast(message);
}
void handle_accept(con_handler::pointer connection, const boost::system::error_code& err)
{
if (!err) {
playerConnections[serverParse::userIdCount++] = connection;
connection -> send_join_message();
}
start_accept();
Player* player = new Player(glm::vec3((7.0f * serverParse::userIdCount) + 3.0f, 3.5f, 3.0f), game, false);
game->allPlayers.push_back(player);
game->allBoundingBoxes.push_back(player->getBoundingBox());
player->setId(serverParse::userIdCount - 1);
if (serverParse::userIdCount == 4)
{
begin_game();
}
}
/*
*Helper function to send a msg to all clients
*/
void broadcast(std::string msg)
{
int x;
for(x = 0; x < serverParse::userIdCount; x++)
playerConnections[x] -> send_game_state(msg);
}
/*
*This function will be called once and will run perpetually.
*Every PERIOD milliseconds, the function will handle one message per
*input queue and broadcast the player info to all connected clients
*/
void handle_timeout()
{
srand(time(NULL));
while (1)
{
std::this_thread::sleep_for(std::chrono::milliseconds(PERIOD));
if (serverParse::userIdCount > 0) {
//first handle incoming messages, if there are any
int bufIndex;
for (bufIndex = 0; bufIndex < serverParse::userIdCount; bufIndex++)
{
std::string nextMessage = playerConnections[bufIndex]->dequeue();
if (!nextMessage.empty())
{
//cout << "Receiving message for player:" << bufIndex << ":" << nextMessage << endl;
serverParse::sortClientMessage(game, nextMessage);
}
}
string inputMessage = "";
if (game)
{
game->update(PERIOD / 1000.0f);
inputMessage = game->getServerInputMessage();
}
broadcast(inputMessage);
}
}
}
};
int main(int argc, char* argv[])
{
try
{
/*
* Set port if available. If not, use default value.
*/
int portNum = 1234;
if (argc > 1) {
portNum = std::stoi(argv[1]);
}
boost::asio::io_service io_service;
Server server(io_service,portNum);
//init state to dummy values
boost::asio::io_service::work idleWork(io_service);
std::thread io_thread = std::thread([&]() {io_service.run();});
std::thread timer_thread = std::thread([&]() {server.handle_timeout();});
std::cout << "Starting loop" << std::endl;
while (1) {
}
}
catch (std::exception& e)
{
std::cerr << e.what() << endl;
}
return 0;
}