-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
94 lines (72 loc) · 2.47 KB
/
main.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
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "wsock32.lib")
#include <iostream>
#include <sstream>
#include "Sockets.hpp"
#include "WebSocketServer.hpp"
class CustomConnection : public WebSocketConnection
{
static int nextId;
int id;
public:
CustomConnection (WebSocketServer* server, Connection conn)
: WebSocketConnection (server, conn), id (0)
{
}
int getId () const
{
return id;
}
void setId ()
{
if (id <= 0)
{
id = nextId++;
}
}
};
int CustomConnection::nextId = 1;
void startServer ()
{
WebSocketServer server;
server.setNewClientCallback ([](WebSocketServer* server, WebSocketConnection* connection)
{
CustomConnection* conn = (CustomConnection*) connection;
conn->setId ();
std::cout << "New client entered with IP: " << connection->getIp () << ", ID: " << conn->getId () << std::endl;
connection->send ("saludo", "hola");
});
server.setClosedClientCallback ([](WebSocketServer* server, WebSocketConnection* connection)
{
CustomConnection* conn = (CustomConnection*) connection;
std::cout << "Client with ID: " << conn->getId () << " disconnected." << std::endl;
});
server.setUnknownMessageCallback ([](WebSocketServer* server, WebSocketConnection* connection, std::string key, std::string data)
{
CustomConnection* conn = (CustomConnection*) connection;
std::cout << "ID: " << conn->getId () << " -> Unknown: [" << key << "] = " << data << std::endl;
});
server.setDataCallback ("Prueba", [](WebSocketServer* server, WebSocketConnection* connection, std::string key, std::string data)
{
CustomConnection* conn = (CustomConnection*) connection;
std::cout << "Id: " << conn->getId () << " -> [" << key << "] = " << data << std::endl;
server->sendPing ();
});
server.setInstantiator ([](WebSocketServer* server, Connection conn)->WebSocketConnection*
{
return new CustomConnection (server, conn);
});
server.setServeFolder("../c-websockets");
server.setDefaultPage("client.html");
if (!server.startAndWait (80))
{
std::cout << "Server couldn't be started" << std::endl;
}
}
int main (int argc, char** argv)
{
startServer ();
std::cout << "Finished" << std::endl;
std::cin.get ();
return 0;
}