This repository has been archived by the owner on Jan 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
enetServer.cpp
65 lines (56 loc) · 1.67 KB
/
enetServer.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
#include "enet.h"
#include <iostream>
#include <string>
#include <stdio.h>
#include <sstream>
#include <cstring>
#include <thread>
using namespace std;
volatile bool quitting = false;
void (*cevent)(ENetPeer*, ENetHost*, ENetEvent) = nullptr;
void (*revent)(ENetPeer*, ENetHost*, ENetEvent) = nullptr;
void (*devent)(ENetPeer*, ENetHost*, ENetEvent) = nullptr;
void server::connect(void (*a)(ENetPeer*, ENetHost*, ENetEvent)){cevent = a;}
void server::recieve(void (*a)(ENetPeer*, ENetHost*, ENetEvent)){revent = a;}
void server::disconnect(void (*a)(ENetPeer*, ENetHost*, ENetEvent)){devent = a;}
void server::send(std::string data, ENetPeer* peer){
ENetPacket *packet = enet_packet_create(data.c_str(), data.size()+1, ENET_PACKET_FLAG_RELIABLE);
enet_peer_send(peer,0,packet);
}
void runThread(int port){
ENetHost *server;
ENetAddress address;
address.host = ENET_HOST_ANY;
address.port = port;
server = enet_host_create(&address, 32, 2, 0, 0);
ENetEvent talking;
while(!quitting){
enet_host_service(server, &talking, 1000);
switch(talking.type){
case ENET_EVENT_TYPE_CONNECT:
if(cevent != nullptr)
cevent(talking.peer, server, talking);
break;
case ENET_EVENT_TYPE_RECEIVE:
if(revent != nullptr)
revent(talking.peer, server, talking);
break;
case ENET_EVENT_TYPE_DISCONNECT:
if(devent != nullptr)
devent(talking.peer, server, talking);
break;
default: break;
}
enet_host_flush(server);
}
enet_host_destroy(server);
enet_deinitialize();
}
std::thread thr;
void server::init(int port) {
thr = std::thread(runThread, port);
}
void server::quit(){
quitting = true;
thr.join();
}