-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebSocketServer.cpp
More file actions
209 lines (182 loc) · 6.09 KB
/
WebSocketServer.cpp
File metadata and controls
209 lines (182 loc) · 6.09 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
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
/** --------------------------------------------------------------------------
* WebSocketServer.cpp
*
* Base class that WebSocket implementations must inherit from. Handles the
* client connections and calls the child class callbacks for connection
* events like onConnect, onMessage, and onDisconnect.
*
* Author : Jason Kruse <jason@jasonkruse.com> or @mnisjk
* Copyright : 2014
* License : BSD (see LICENSE)
* --------------------------------------------------------------------------
**/
#include <stdlib.h>
#include <string.h>
//#include <sys/time.h>
#include <fcntl.h>
#include "WebSocketServer.h"
using namespace std;
// 0 for unlimited
#define MAX_BUFFER_SIZE 0
// Nasty hack because certain callbacks are statically defined
WebSocketServer *self;
static int callback_main( struct lws *wsi,
enum lws_callback_reasons reason,
void *user,
void *in,
size_t len )
{
int fd;
static unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1024 + LWS_SEND_BUFFER_POST_PADDING];
unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
switch( reason ) {
case LWS_CALLBACK_ESTABLISHED:
self->onConnectWrapper( lws_get_socket_fd( wsi ) );
lws_callback_on_writable( wsi );
break;
case LWS_CALLBACK_SERVER_WRITEABLE:
fd = lws_get_socket_fd( wsi );
while( !self->connections[fd]->buffer.empty( ) )
{
WriteByteArray* wb = self->connections[fd]->buffer.front( );
int length = 0;
unsigned char* data = (unsigned char*)wb->getBuffer(length);
memcpy(p, data, length);
int charsSent = lws_write(wsi, buf + LWS_SEND_BUFFER_PRE_PADDING, length, LWS_WRITE_BINARY);
if (charsSent < length)
self->onErrorWrapper( fd, string( "Error writing to socket" ) );
else
{
// Only pop the message if it was sent successfully.
self->connections[fd]->buffer.pop_front();
delete wb;
}
}
lws_callback_on_writable( wsi );
break;
case LWS_CALLBACK_RECEIVE:
self->onMessage(wsi, in, len);
break;
case LWS_CALLBACK_CLOSED:
self->onDisconnectWrapper( lws_get_socket_fd( wsi ) );
break;
default:
break;
}
return 0;
}
static struct lws_protocols protocols[] = {
{
"",
callback_main,
0, // user data struct not used
MAX_BUFFER_SIZE,
},{ NULL, NULL, 0, 0 } // terminator
};
WebSocketServer::WebSocketServer( int port, const string certPath, const string& keyPath )
{
this->_port = port;
this->_certPath = certPath;
this->_keyPath = keyPath;
_receivedData.reserve(WS_RESERVE_RECEIVE_BUFFER_SIZE);
lws_set_log_level( 0, lwsl_emit_syslog ); // We'll do our own logging, thank you.
struct lws_context_creation_info info;
memset( &info, 0, sizeof info );
info.port = this->_port;
info.iface = NULL;
info.protocols = protocols;
#ifndef LWS_NO_EXTENSIONS
info.extensions = lws_get_internal_extensions( );
#endif
if( !this->_certPath.empty( ) && !this->_keyPath.empty( ) )
{
info.ssl_cert_filepath = this->_certPath.c_str( );
info.ssl_private_key_filepath = this->_keyPath.c_str( );
}
else
{
info.ssl_cert_filepath = NULL;
info.ssl_private_key_filepath = NULL;
}
info.gid = -1;
info.uid = -1;
info.options = 0;
// keep alive
info.ka_time = 60; // 60 seconds until connection is suspicious
info.ka_probes = 10; // 10 probes after ^ time
info.ka_interval = 10; // 10s interval for sending probes
this->_context = lws_create_context( &info );
if( !this->_context )
throw "libwebsocket init failed";
// Some of the libwebsocket stuff is define statically outside the class. This
// allows us to call instance variables from the outside. Unfortunately this
// means some attributes must be public that otherwise would be private.
self = this;
}
WebSocketServer::~WebSocketServer( )
{
// Free up some memory
for( map<int,Connection*>::const_iterator it = this->connections.begin( ); it != this->connections.end( ); ++it )
{
Connection* c = it->second;
this->connections.erase( it->first );
delete c;
}
}
void WebSocketServer::onConnectWrapper( int socketID )
{
Connection* c = new Connection;
c->createTime = time( 0 );
this->connections[ socketID ] = c;
this->onConnect( socketID );
}
void WebSocketServer::onDisconnectWrapper( int socketID )
{
this->onDisconnect( socketID );
this->_removeConnection( socketID );
}
void WebSocketServer::onErrorWrapper( int socketID, const string& message )
{
this->onError( socketID, message );
this->_removeConnection( socketID );
}
void WebSocketServer::send(int socketID, WriteByteArray* wb)
{
// Push this onto the buffer. It will be written out when the socket is writable.
this->connections[socketID]->buffer.push_back( wb );
}
void WebSocketServer::broadcast(WriteByteArray* wb)
{
for( map<int,Connection*>::const_iterator it = this->connections.begin( ); it != this->connections.end( ); ++it )
this->send( it->first, wb );
}
void WebSocketServer::setValue( int socketID, const string& name, const string& value )
{
this->connections[socketID]->keyValueMap[name] = value;
}
string WebSocketServer::getValue( int socketID, const string& name )
{
return this->connections[socketID]->keyValueMap[name];
}
int WebSocketServer::getNumberOfConnections( )
{
return this->connections.size( );
}
void WebSocketServer::run( uint64_t timeout )
{
while( 1 )
{
this->wait( timeout );
}
}
void WebSocketServer::wait( uint64_t timeout )
{
if( lws_service( this->_context, timeout ) < 0 )
throw "Error polling for socket activity.";
}
void WebSocketServer::_removeConnection( int socketID )
{
Connection* c = this->connections[ socketID ];
this->connections.erase( socketID );
delete c;
}