forked from m-byte918/AgarOSS
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGameServer.h
More file actions
82 lines (73 loc) · 2.43 KB
/
GameServer.h
File metadata and controls
82 lines (73 loc) · 2.43 KB
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
#pragma once
#include <uWS/uWS.h>
//#include "Player.h"
#include "Modules/Logger.h"
#include "Entity/EntityHandler.h"
// todo: put implementation of functions in .cpp
// for some reason g++ doesn't like it when i do that
class Game {
private:
uWS::Hub hub;
uint64_t serverConnections;
uint64_t tickCount = 0;
public:
void onClientConnection() {
hub.onConnection([&](uWS::WebSocket<uWS::SERVER> *ws, uWS::HttpRequest req) {
if (++serverConnections > cfg::maxConnections) {
ws->close(1000, "Server connection limit reached");
return;
}
std::cout << "connection made\n";
//ws->setUserData(new Player);
//ws->send();
});
}
void onClientDisconnection() {
hub.onDisconnection([&](uWS::WebSocket<uWS::SERVER> *ws, int code, char *message, size_t length) {
//std::cout << code << "\n";
std::cout << "disconnection\n";
serverConnections--;
});
}
void onClientMessage() {
hub.onMessage([](uWS::WebSocket<uWS::SERVER> *ws, char *message, size_t length, uWS::OpCode opCode) {
std::cout << "message recieved\n";
if (length > 256) {
ws->close(1009, "Spam");
}
});
}
void run() {
tickCount++;
std::cout << (int)tickCount << "\n";
onClientConnection();
onClientDisconnection();
onClientMessage();
}
Game() {
logger::start();
std::string port_str = std::to_string(cfg::serverPort);
if (hub.listen(cfg::serverPort)) {
hub.connect("ws://localhost:" + port_str, nullptr);
std::cout << "Server is listening on port " << port_str << "\n";
} else {
std::cout << "Server couldn't listen on port " << port_str << "\n";
return;
}
// Spawn starting entities
ent::spawnStartingEntities();
Timer *timer = new Timer(hub.getLoop());
timer->setData((void*) this);
timer->start([](Timer *timer) {
//auto *timerData = (Game*)timer->getData();
//timerData->run();
((Game*)timer->getData())->run();
}, 0, cfg::tickStep);
hub.run();
}
~Game() {
logger::end(); // Shutdown logger
ent::removeAll(); // Remove entities
hub.getDefaultGroup<uWS::SERVER>().close(); // Close server
}
};