2 * libwebsockets-test-server-extpoll - libwebsockets external poll loop sample
4 * This acts the same as libwebsockets-test-server but works with the poll
5 * loop taken out of libwebsockets and into this app. It's an example of how
6 * you can integrate libwebsockets polling into an app that already has its
9 * Copyright (C) 2010-2011 Andy Green <andy@warmcat.com>
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation:
14 * version 2.1 of the License.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
34 #include "../win32port/win32helpers/websock-w32.h"
37 #include "../win32port/win32helpers/websock-w32.h"
43 #include "../lib/libwebsockets.h"
47 * This demo server shows how to use libwebsockets for one or more
48 * websocket protocols in the same server
50 * It defines the following websocket protocols:
52 * dumb-increment-protocol: once the socket is opened, an incrementing
53 * ascii string is sent down it every 50ms.
54 * If you send "reset\n" on the websocket, then
55 * the incrementing number is reset to 0.
57 * lws-mirror-protocol: copies any received packet to every connection also
58 * using this protocol, including the sender
61 #define MAX_POLL_ELEMENTS 100
62 struct pollfd pollfds[100];
63 int count_pollfds = 0;
71 PROTOCOL_DUMB_INCREMENT,
79 #define LOCAL_RESOURCE_PATH INSTALL_DATADIR"/libwebsockets-test-server"
81 /* this protocol server (always the first one) just knows how to do HTTP */
83 static int callback_http(struct libwebsocket_context * this,
84 struct libwebsocket *wsi,
85 enum libwebsocket_callback_reasons reason, void *user,
89 char client_name[128];
93 case LWS_CALLBACK_HTTP:
94 fprintf(stderr, "serving HTTP URI %s\n", (char *)in);
96 if (in && strcmp(in, "/favicon.ico") == 0) {
97 if (libwebsockets_serve_http_file(wsi,
98 LOCAL_RESOURCE_PATH"/favicon.ico", "image/x-icon"))
99 fprintf(stderr, "Failed to send favicon\n");
103 /* send the script... when it runs it'll start websockets */
105 if (libwebsockets_serve_http_file(wsi,
106 LOCAL_RESOURCE_PATH"/test.html", "text/html"))
107 fprintf(stderr, "Failed to send HTTP file\n");
108 /* we are done with this connnection */
112 * callback for confirming to continue with client IP appear in
113 * protocol 0 callback since no websocket protocol has been agreed
114 * yet. You can just ignore this if you won't filter on client IP
115 * since the default uhandled callback return is 0 meaning let the
116 * connection continue.
119 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
121 libwebsockets_get_peer_addresses((int)(long)user, client_name,
122 sizeof(client_name), client_ip, sizeof(client_ip));
124 fprintf(stderr, "Received network connect from %s (%s)\n",
125 client_name, client_ip);
127 /* if we returned non-zero from here, we kill the connection */
131 * callbacks for managing the external poll() array appear in
132 * protocol 0 callback
135 case LWS_CALLBACK_ADD_POLL_FD:
136 pollfds[count_pollfds].fd = (int)(long)user;
137 pollfds[count_pollfds].events = (int)len;
138 pollfds[count_pollfds++].revents = 0;
141 case LWS_CALLBACK_DEL_POLL_FD:
142 for (n = 0; n < count_pollfds; n++) {
143 if (pollfds[n].fd != (int)(long)user)
146 * swap the end guy into our vacant slot...
147 * works ok if n is the end guy
149 pollfds[n] = pollfds[count_pollfds - 1];
150 pollfds[count_pollfds - 1].fd = -1;
156 case LWS_CALLBACK_SET_MODE_POLL_FD:
157 for (n = 0; n < count_pollfds; n++)
158 if (pollfds[n].fd == (int)(long)user)
159 pollfds[n].events |= (int)(long)len;
162 case LWS_CALLBACK_CLEAR_MODE_POLL_FD:
163 for (n = 0; n < count_pollfds; n++)
164 if (pollfds[n].fd == (int)(long)user)
165 pollfds[n].events &= ~(int)(long)len;
176 * this is just an example of parsing handshake headers, you don't need this
177 * in your code unless you will filter allowing connections by the header
182 dump_handshake_info(struct lws_tokens *lwst)
185 static const char *token_names[] = {
186 [WSI_TOKEN_GET_URI] = "GET URI",
187 [WSI_TOKEN_HOST] = "Host",
188 [WSI_TOKEN_CONNECTION] = "Connection",
189 [WSI_TOKEN_KEY1] = "key 1",
190 [WSI_TOKEN_KEY2] = "key 2",
191 [WSI_TOKEN_PROTOCOL] = "Protocol",
192 [WSI_TOKEN_UPGRADE] = "Upgrade",
193 [WSI_TOKEN_ORIGIN] = "Origin",
194 [WSI_TOKEN_DRAFT] = "Draft",
195 [WSI_TOKEN_CHALLENGE] = "Challenge",
198 [WSI_TOKEN_KEY] = "Key",
199 [WSI_TOKEN_VERSION] = "Version",
200 [WSI_TOKEN_SWORIGIN] = "Sworigin",
203 [WSI_TOKEN_EXTENSIONS] = "Extensions",
205 /* client receives these */
206 [WSI_TOKEN_ACCEPT] = "Accept",
207 [WSI_TOKEN_NONCE] = "Nonce",
208 [WSI_TOKEN_HTTP] = "Http",
209 [WSI_TOKEN_MUXURL] = "MuxURL",
212 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
213 if (lwst[n].token == NULL)
216 fprintf(stderr, " %s = %s\n", token_names[n], lwst[n].token);
220 /* dumb_increment protocol */
223 * one of these is auto-created for each connection and a pointer to the
224 * appropriate instance is passed to the callback in the user parameter
226 * for this example protocol we use it to individualize the count for each
230 struct per_session_data__dumb_increment {
235 callback_dumb_increment(struct libwebsocket_context * this,
236 struct libwebsocket *wsi,
237 enum libwebsocket_callback_reasons reason,
238 void *user, void *in, size_t len)
241 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 +
242 LWS_SEND_BUFFER_POST_PADDING];
243 unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
244 struct per_session_data__dumb_increment *pss = user;
248 case LWS_CALLBACK_ESTABLISHED:
253 * in this protocol, we just use the broadcast action as the chance to
254 * send our own connection-specific data and ignore the broadcast info
255 * that is available in the 'in' parameter
258 case LWS_CALLBACK_BROADCAST:
259 n = sprintf((char *)p, "%d", pss->number++);
260 n = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
262 fprintf(stderr, "ERROR %d writing to socket\n", n);
267 case LWS_CALLBACK_RECEIVE:
268 fprintf(stderr, "rx %d\n", (int)len);
271 if (strcmp(in, "reset\n") == 0)
276 * this just demonstrates how to use the protocol filter. If you won't
277 * study and reject connections based on header content, you don't need
278 * to handle this callback
281 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
282 dump_handshake_info((struct lws_tokens *)(long)user);
283 /* you could return non-zero here and kill the connection */
294 /* lws-mirror_protocol */
296 #define MAX_MESSAGE_QUEUE 64
298 struct per_session_data__lws_mirror {
299 struct libwebsocket *wsi;
308 static struct a_message ringbuffer[MAX_MESSAGE_QUEUE];
309 static int ringbuffer_head;
313 callback_lws_mirror(struct libwebsocket_context * this,
314 struct libwebsocket *wsi,
315 enum libwebsocket_callback_reasons reason,
316 void *user, void *in, size_t len)
319 struct per_session_data__lws_mirror *pss = user;
323 case LWS_CALLBACK_ESTABLISHED:
324 pss->ringbuffer_tail = ringbuffer_head;
326 libwebsocket_callback_on_writable(this, wsi);
329 case LWS_CALLBACK_SERVER_WRITEABLE:
331 if (pss->ringbuffer_tail != ringbuffer_head) {
333 n = libwebsocket_write(wsi, (unsigned char *)
334 ringbuffer[pss->ringbuffer_tail].payload +
335 LWS_SEND_BUFFER_PRE_PADDING,
336 ringbuffer[pss->ringbuffer_tail].len,
340 fprintf(stderr, "ERROR %d writing to socket\n", n);
344 if (pss->ringbuffer_tail == (MAX_MESSAGE_QUEUE - 1))
345 pss->ringbuffer_tail = 0;
347 pss->ringbuffer_tail++;
349 if (((ringbuffer_head - pss->ringbuffer_tail) %
350 MAX_MESSAGE_QUEUE) < (MAX_MESSAGE_QUEUE - 15))
351 libwebsocket_rx_flow_control(wsi, 1);
353 libwebsocket_callback_on_writable(this, wsi);
358 case LWS_CALLBACK_BROADCAST:
359 n = libwebsocket_write(wsi, in, len, LWS_WRITE_TEXT);
361 fprintf(stderr, "mirror write failed\n");
364 case LWS_CALLBACK_RECEIVE:
366 if (ringbuffer[ringbuffer_head].payload)
367 free(ringbuffer[ringbuffer_head].payload);
369 ringbuffer[ringbuffer_head].payload =
370 malloc(LWS_SEND_BUFFER_PRE_PADDING + len +
371 LWS_SEND_BUFFER_POST_PADDING);
372 ringbuffer[ringbuffer_head].len = len;
373 memcpy((char *)ringbuffer[ringbuffer_head].payload +
374 LWS_SEND_BUFFER_PRE_PADDING, in, len);
375 if (ringbuffer_head == (MAX_MESSAGE_QUEUE - 1))
380 if (((ringbuffer_head - pss->ringbuffer_tail) %
381 MAX_MESSAGE_QUEUE) > (MAX_MESSAGE_QUEUE - 10))
382 libwebsocket_rx_flow_control(wsi, 0);
384 libwebsocket_callback_on_writable_all_protocol(
385 libwebsockets_get_protocol(wsi));
389 * this just demonstrates how to use the protocol filter. If you won't
390 * study and reject connections based on header content, you don't need
391 * to handle this callback
394 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
395 dump_handshake_info((struct lws_tokens *)(long)user);
396 /* you could return non-zero here and kill the connection */
407 /* list of supported protocols and callbacks */
409 static struct libwebsocket_protocols protocols[] = {
410 /* first protocol must always be HTTP handler */
413 "http-only", /* name */
414 callback_http, /* callback */
415 0 /* per_session_data_size */
418 "dumb-increment-protocol",
419 callback_dumb_increment,
420 sizeof(struct per_session_data__dumb_increment),
423 "lws-mirror-protocol",
425 sizeof(struct per_session_data__lws_mirror)
428 NULL, NULL, 0 /* End of list */
432 static struct option options[] = {
433 { "help", no_argument, NULL, 'h' },
434 { "debug", required_argument, NULL, 'd' },
435 { "port", required_argument, NULL, 'p' },
436 { "ssl", no_argument, NULL, 's' },
437 { "killmask", no_argument, NULL, 'k' },
438 { "interface", required_argument, NULL, 'i' },
442 int main(int argc, char **argv)
445 const char *cert_path =
446 LOCAL_RESOURCE_PATH"/libwebsockets-test-server.pem";
447 const char *key_path =
448 LOCAL_RESOURCE_PATH"/libwebsockets-test-server.key.pem";
449 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1024 +
450 LWS_SEND_BUFFER_POST_PADDING];
453 struct libwebsocket_context *context;
455 unsigned int oldus = 0;
456 char interface_name[128] = "";
457 const char *interface_ptr = NULL;
459 fprintf(stderr, "libwebsockets test server with external poll()\n"
460 "(C) Copyright 2010-2011 Andy Green <andy@warmcat.com> "
461 "licensed under LGPL2.1\n");
464 n = getopt_long(argc, argv, "i:khsp:d:", options, NULL);
469 lws_set_log_level(atoi(optarg), NULL);
475 opts = LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK;
481 strncpy(interface_name, optarg, sizeof interface_name);
482 interface_name[(sizeof interface_name) - 1] = '\0';
483 interface_ptr = interface_name;
486 fprintf(stderr, "Usage: test-server "
487 "[--port=<p>] [--ssl] "
488 "[-d <log bitfield>]\n");
494 cert_path = key_path = NULL;
496 context = libwebsocket_create_context(port, interface_ptr, protocols,
497 libwebsocket_internal_extensions,
498 cert_path, key_path, NULL, -1, -1,
500 if (context == NULL) {
501 fprintf(stderr, "libwebsocket init failed\n");
505 buf[LWS_SEND_BUFFER_PRE_PADDING] = 'x';
508 * This is an example of an existing application's explicit poll()
509 * loop that libwebsockets can integrate with.
516 * this represents an existing server's single poll action
517 * which also includes libwebsocket sockets
520 n = poll(pollfds, count_pollfds, 25);
525 for (n = 0; n < count_pollfds; n++)
526 if (pollfds[n].revents)
528 * returns immediately if the fd does not
529 * match anything under libwebsockets
532 if (libwebsocket_service_fd(context,
536 /* do our broadcast periodically */
538 gettimeofday(&tv, NULL);
541 * This broadcasts to all dumb-increment-protocol connections
544 * We're just sending a character 'x', in these examples the
545 * callbacks send their own per-connection content.
547 * You have to send something with nonzero length to get the
548 * callback actions delivered.
550 * We take care of pre-and-post padding allocation.
553 if (((unsigned int)tv.tv_usec - oldus) > 50000) {
554 libwebsockets_broadcast(
555 &protocols[PROTOCOL_DUMB_INCREMENT],
556 &buf[LWS_SEND_BUFFER_PRE_PADDING], 1);
562 libwebsocket_context_destroy(context);