2 * libwebsockets-test-server - libwebsockets test implementation
4 * Copyright (C) 2010-2011 Andy Green <andy@warmcat.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation:
9 * version 2.1 of the License.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
29 #include "../lib/libwebsockets.h"
33 * This demo server shows how to use libwebsockets for one or more
34 * websocket protocols in the same server
36 * It defines the following websocket protocols:
38 * dumb-increment-protocol: once the socket is opened, an incrementing
39 * ascii string is sent down it every 50ms.
40 * If you send "reset\n" on the websocket, then
41 * the incrementing number is reset to 0.
43 * lws-mirror-protocol: copies any received packet to every connection also
44 * using this protocol, including the sender
51 PROTOCOL_DUMB_INCREMENT,
59 #define LOCAL_RESOURCE_PATH DATADIR"/libwebsockets-test-server"
61 /* this protocol server (always the first one) just knows how to do HTTP */
63 static int callback_http(struct libwebsocket_context * this,
64 struct libwebsocket *wsi,
65 enum libwebsocket_callback_reasons reason, void *user,
68 char client_name[128];
72 case LWS_CALLBACK_HTTP:
73 fprintf(stderr, "serving HTTP URI %s\n", (char *)in);
75 if (in && strcmp(in, "/favicon.ico") == 0) {
76 if (libwebsockets_serve_http_file(wsi,
77 LOCAL_RESOURCE_PATH"/favicon.ico", "image/x-icon"))
78 fprintf(stderr, "Failed to send favicon\n");
82 /* send the script... when it runs it'll start websockets */
84 if (libwebsockets_serve_http_file(wsi,
85 LOCAL_RESOURCE_PATH"/test.html", "text/html"))
86 fprintf(stderr, "Failed to send HTTP file\n");
90 * callback for confirming to continue with client IP appear in
91 * protocol 0 callback since no websocket protocol has been agreed
92 * yet. You can just ignore this if you won't filter on client IP
93 * since the default uhandled callback return is 0 meaning let the
94 * connection continue.
97 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
99 libwebsockets_get_peer_addresses((int)(long)user, client_name,
100 sizeof(client_name), client_ip, sizeof(client_ip));
102 fprintf(stderr, "Received network connect from %s (%s)\n",
103 client_name, client_ip);
105 /* if we returned non-zero from here, we kill the connection */
117 * this is just an example of parsing handshake headers, you don't need this
118 * in your code unless you will filter allowing connections by the header
123 dump_handshake_info(struct lws_tokens *lwst)
126 static const char *token_names[] = {
127 [WSI_TOKEN_GET_URI] = "GET URI",
128 [WSI_TOKEN_HOST] = "Host",
129 [WSI_TOKEN_CONNECTION] = "Connection",
130 [WSI_TOKEN_KEY1] = "key 1",
131 [WSI_TOKEN_KEY2] = "key 2",
132 [WSI_TOKEN_PROTOCOL] = "Protocol",
133 [WSI_TOKEN_UPGRADE] = "Upgrade",
134 [WSI_TOKEN_ORIGIN] = "Origin",
135 [WSI_TOKEN_DRAFT] = "Draft",
136 [WSI_TOKEN_CHALLENGE] = "Challenge",
139 [WSI_TOKEN_KEY] = "Key",
140 [WSI_TOKEN_VERSION] = "Version",
141 [WSI_TOKEN_SWORIGIN] = "Sworigin",
144 [WSI_TOKEN_EXTENSIONS] = "Extensions",
146 /* client receives these */
147 [WSI_TOKEN_ACCEPT] = "Accept",
148 [WSI_TOKEN_NONCE] = "Nonce",
149 [WSI_TOKEN_HTTP] = "Http",
152 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
153 if (lwst[n].token == NULL)
156 fprintf(stderr, " %s = %s\n", token_names[n], lwst[n].token);
160 /* dumb_increment protocol */
163 * one of these is auto-created for each connection and a pointer to the
164 * appropriate instance is passed to the callback in the user parameter
166 * for this example protocol we use it to individualize the count for each
170 struct per_session_data__dumb_increment {
175 callback_dumb_increment(struct libwebsocket_context * this,
176 struct libwebsocket *wsi,
177 enum libwebsocket_callback_reasons reason,
178 void *user, void *in, size_t len)
181 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 +
182 LWS_SEND_BUFFER_POST_PADDING];
183 unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
184 struct per_session_data__dumb_increment *pss = user;
188 case LWS_CALLBACK_ESTABLISHED:
193 * in this protocol, we just use the broadcast action as the chance to
194 * send our own connection-specific data and ignore the broadcast info
195 * that is available in the 'in' parameter
198 case LWS_CALLBACK_BROADCAST:
199 n = sprintf((char *)p, "%d", pss->number++);
200 n = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
202 fprintf(stderr, "ERROR writing to socket");
207 case LWS_CALLBACK_RECEIVE:
208 fprintf(stderr, "rx %d\n", (int)len);
211 if (strcmp(in, "reset\n") == 0)
215 * this just demonstrates how to use the protocol filter. If you won't
216 * study and reject connections based on header content, you don't need
217 * to handle this callback
220 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
221 dump_handshake_info((struct lws_tokens *)(long)user);
222 /* you could return non-zero here and kill the connection */
233 /* lws-mirror_protocol */
235 #define MAX_MESSAGE_QUEUE 64
237 struct per_session_data__lws_mirror {
238 struct libwebsocket *wsi;
247 static struct a_message ringbuffer[MAX_MESSAGE_QUEUE];
248 static int ringbuffer_head;
252 callback_lws_mirror(struct libwebsocket_context * this,
253 struct libwebsocket *wsi,
254 enum libwebsocket_callback_reasons reason,
255 void *user, void *in, size_t len)
258 struct per_session_data__lws_mirror *pss = user;
262 case LWS_CALLBACK_ESTABLISHED:
263 pss->ringbuffer_tail = ringbuffer_head;
267 case LWS_CALLBACK_CLIENT_WRITEABLE:
268 if (pss->ringbuffer_tail != ringbuffer_head) {
270 n = libwebsocket_write(wsi, (unsigned char *)
271 ringbuffer[pss->ringbuffer_tail].payload +
272 LWS_SEND_BUFFER_PRE_PADDING,
273 ringbuffer[pss->ringbuffer_tail].len,
276 fprintf(stderr, "ERROR writing to socket");
280 if (pss->ringbuffer_tail == (MAX_MESSAGE_QUEUE - 1))
281 pss->ringbuffer_tail = 0;
283 pss->ringbuffer_tail++;
285 if (((ringbuffer_head - pss->ringbuffer_tail) %
286 MAX_MESSAGE_QUEUE) < (MAX_MESSAGE_QUEUE - 15))
287 libwebsocket_rx_flow_control(wsi, 1);
289 libwebsocket_callback_on_writable(this, wsi);
294 case LWS_CALLBACK_BROADCAST:
295 n = libwebsocket_write(wsi, in, len, LWS_WRITE_TEXT);
297 fprintf(stderr, "mirror write failed\n");
300 case LWS_CALLBACK_RECEIVE:
302 if (ringbuffer[ringbuffer_head].payload)
303 free(ringbuffer[ringbuffer_head].payload);
305 ringbuffer[ringbuffer_head].payload =
306 malloc(LWS_SEND_BUFFER_PRE_PADDING + len +
307 LWS_SEND_BUFFER_POST_PADDING);
308 ringbuffer[ringbuffer_head].len = len;
309 memcpy((char *)ringbuffer[ringbuffer_head].payload +
310 LWS_SEND_BUFFER_PRE_PADDING, in, len);
311 if (ringbuffer_head == (MAX_MESSAGE_QUEUE - 1))
316 if (((ringbuffer_head - pss->ringbuffer_tail) %
317 MAX_MESSAGE_QUEUE) > (MAX_MESSAGE_QUEUE - 10))
318 libwebsocket_rx_flow_control(wsi, 0);
320 libwebsocket_callback_on_writable_all_protocol(
321 libwebsockets_get_protocol(wsi));
324 * this just demonstrates how to use the protocol filter. If you won't
325 * study and reject connections based on header content, you don't need
326 * to handle this callback
329 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
330 dump_handshake_info((struct lws_tokens *)(long)user);
331 /* you could return non-zero here and kill the connection */
342 /* list of supported protocols and callbacks */
344 static struct libwebsocket_protocols protocols[] = {
345 /* first protocol must always be HTTP handler */
348 .callback = callback_http,
350 [PROTOCOL_DUMB_INCREMENT] = {
351 .name = "dumb-increment-protocol",
352 .callback = callback_dumb_increment,
353 .per_session_data_size =
354 sizeof(struct per_session_data__dumb_increment),
356 [PROTOCOL_LWS_MIRROR] = {
357 .name = "lws-mirror-protocol",
358 .callback = callback_lws_mirror,
359 .per_session_data_size =
360 sizeof(struct per_session_data__lws_mirror),
362 [DEMO_PROTOCOL_COUNT] = { /* end of list */
367 static struct option options[] = {
368 { "help", no_argument, NULL, 'h' },
369 { "port", required_argument, NULL, 'p' },
370 { "ssl", no_argument, NULL, 's' },
371 { "killmask", no_argument, NULL, 'k' },
372 { "interface", required_argument, NULL, 'i' },
376 int main(int argc, char **argv)
379 const char *cert_path =
380 LOCAL_RESOURCE_PATH"/libwebsockets-test-server.pem";
381 const char *key_path =
382 LOCAL_RESOURCE_PATH"/libwebsockets-test-server.key.pem";
383 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1024 +
384 LWS_SEND_BUFFER_POST_PADDING];
387 struct libwebsocket_context *context;
389 char interface_name[128] = "";
390 const char * interface = NULL;
392 unsigned int oldus = 0;
395 fprintf(stderr, "libwebsockets test server\n"
396 "(C) Copyright 2010-2011 Andy Green <andy@warmcat.com> "
397 "licensed under LGPL2.1\n");
400 n = getopt_long(argc, argv, "i:khsp:", options, NULL);
408 opts = LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK;
414 strncpy(interface_name, optarg, sizeof interface_name);
415 interface_name[(sizeof interface_name) - 1] = '\0';
416 interface = interface_name;
419 fprintf(stderr, "Usage: test-server "
420 "[--port=<p>] [--ssl]\n");
426 cert_path = key_path = NULL;
428 context = libwebsocket_create_context(port, interface, protocols,
429 cert_path, key_path, -1, -1, opts);
430 if (context == NULL) {
431 fprintf(stderr, "libwebsocket init failed\n");
435 buf[LWS_SEND_BUFFER_PRE_PADDING] = 'x';
440 * This example shows how to work with no forked service loop
443 fprintf(stderr, " Using no-fork service loop\n");
448 gettimeofday(&tv, NULL);
451 * This broadcasts to all dumb-increment-protocol connections
454 * We're just sending a character 'x', in these examples the
455 * callbacks send their own per-connection content.
457 * You have to send something with nonzero length to get the
458 * callback actions delivered.
460 * We take care of pre-and-post padding allocation.
463 if (((unsigned int)tv.tv_usec - oldus) > 50000) {
464 libwebsockets_broadcast(
465 &protocols[PROTOCOL_DUMB_INCREMENT],
466 &buf[LWS_SEND_BUFFER_PRE_PADDING], 1);
471 * This example server does not fork or create a thread for
472 * websocket service, it all runs in this single loop. So,
473 * we have to give the websockets an opportunity to service
476 * If no socket is needing service, the call below returns
477 * immediately and quickly.
480 libwebsocket_service(context, 50);
486 * This example shows how to work with the forked websocket service loop
489 fprintf(stderr, " Using forked service loop\n");
492 * This forks the websocket service action into a subprocess so we
493 * don't have to take care about it.
496 n = libwebsockets_fork_service_loop(context);
498 fprintf(stderr, "Unable to fork service loop %d\n", n);
507 * This broadcasts to all dumb-increment-protocol connections
510 * We're just sending a character 'x', in these examples the
511 * callbacks send their own per-connection content.
513 * You have to send something with nonzero length to get the
514 * callback actions delivered.
516 * We take care of pre-and-post padding allocation.
519 libwebsockets_broadcast(&protocols[PROTOCOL_DUMB_INCREMENT],
520 &buf[LWS_SEND_BUFFER_PRE_PADDING], 1);
525 libwebsocket_context_destroy(context);