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)
144 while (n < count_pollfds) {
145 pollfds[n] = pollfds[n + 1];
151 case LWS_CALLBACK_SET_MODE_POLL_FD:
152 for (n = 0; n < count_pollfds; n++)
153 if (pollfds[n].fd == (int)(long)user)
154 pollfds[n].events |= (int)(long)len;
157 case LWS_CALLBACK_CLEAR_MODE_POLL_FD:
158 for (n = 0; n < count_pollfds; n++)
159 if (pollfds[n].fd == (int)(long)user)
160 pollfds[n].events &= ~(int)(long)len;
171 * this is just an example of parsing handshake headers, you don't need this
172 * in your code unless you will filter allowing connections by the header
177 dump_handshake_info(struct lws_tokens *lwst)
180 static const char *token_names[] = {
181 [WSI_TOKEN_GET_URI] = "GET URI",
182 [WSI_TOKEN_HOST] = "Host",
183 [WSI_TOKEN_CONNECTION] = "Connection",
184 [WSI_TOKEN_KEY1] = "key 1",
185 [WSI_TOKEN_KEY2] = "key 2",
186 [WSI_TOKEN_PROTOCOL] = "Protocol",
187 [WSI_TOKEN_UPGRADE] = "Upgrade",
188 [WSI_TOKEN_ORIGIN] = "Origin",
189 [WSI_TOKEN_DRAFT] = "Draft",
190 [WSI_TOKEN_CHALLENGE] = "Challenge",
193 [WSI_TOKEN_KEY] = "Key",
194 [WSI_TOKEN_VERSION] = "Version",
195 [WSI_TOKEN_SWORIGIN] = "Sworigin",
198 [WSI_TOKEN_EXTENSIONS] = "Extensions",
200 /* client receives these */
201 [WSI_TOKEN_ACCEPT] = "Accept",
202 [WSI_TOKEN_NONCE] = "Nonce",
203 [WSI_TOKEN_HTTP] = "Http",
204 [WSI_TOKEN_MUXURL] = "MuxURL",
207 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
208 if (lwst[n].token == NULL)
211 fprintf(stderr, " %s = %s\n", token_names[n], lwst[n].token);
215 /* dumb_increment protocol */
218 * one of these is auto-created for each connection and a pointer to the
219 * appropriate instance is passed to the callback in the user parameter
221 * for this example protocol we use it to individualize the count for each
225 struct per_session_data__dumb_increment {
230 callback_dumb_increment(struct libwebsocket_context * this,
231 struct libwebsocket *wsi,
232 enum libwebsocket_callback_reasons reason,
233 void *user, void *in, size_t len)
236 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 +
237 LWS_SEND_BUFFER_POST_PADDING];
238 unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
239 struct per_session_data__dumb_increment *pss = user;
243 case LWS_CALLBACK_ESTABLISHED:
248 * in this protocol, we just use the broadcast action as the chance to
249 * send our own connection-specific data and ignore the broadcast info
250 * that is available in the 'in' parameter
253 case LWS_CALLBACK_BROADCAST:
254 n = sprintf((char *)p, "%d", pss->number++);
255 n = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
257 fprintf(stderr, "ERROR writing to socket");
262 case LWS_CALLBACK_RECEIVE:
263 fprintf(stderr, "rx %d\n", (int)len);
266 if (strcmp(in, "reset\n") == 0)
271 * this just demonstrates how to use the protocol filter. If you won't
272 * study and reject connections based on header content, you don't need
273 * to handle this callback
276 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
277 dump_handshake_info((struct lws_tokens *)(long)user);
278 /* you could return non-zero here and kill the connection */
289 /* lws-mirror_protocol */
291 #define MAX_MESSAGE_QUEUE 64
293 struct per_session_data__lws_mirror {
294 struct libwebsocket *wsi;
303 static struct a_message ringbuffer[MAX_MESSAGE_QUEUE];
304 static int ringbuffer_head;
308 callback_lws_mirror(struct libwebsocket_context * this,
309 struct libwebsocket *wsi,
310 enum libwebsocket_callback_reasons reason,
311 void *user, void *in, size_t len)
314 struct per_session_data__lws_mirror *pss = user;
318 case LWS_CALLBACK_ESTABLISHED:
319 pss->ringbuffer_tail = ringbuffer_head;
321 libwebsocket_callback_on_writable(this, wsi);
324 case LWS_CALLBACK_SERVER_WRITEABLE:
326 if (pss->ringbuffer_tail != ringbuffer_head) {
328 n = libwebsocket_write(wsi, (unsigned char *)
329 ringbuffer[pss->ringbuffer_tail].payload +
330 LWS_SEND_BUFFER_PRE_PADDING,
331 ringbuffer[pss->ringbuffer_tail].len,
335 fprintf(stderr, "ERROR writing to socket");
339 if (pss->ringbuffer_tail == (MAX_MESSAGE_QUEUE - 1))
340 pss->ringbuffer_tail = 0;
342 pss->ringbuffer_tail++;
344 if (((ringbuffer_head - pss->ringbuffer_tail) %
345 MAX_MESSAGE_QUEUE) < (MAX_MESSAGE_QUEUE - 15))
346 libwebsocket_rx_flow_control(wsi, 1);
348 libwebsocket_callback_on_writable(this, wsi);
353 case LWS_CALLBACK_BROADCAST:
354 n = libwebsocket_write(wsi, in, len, LWS_WRITE_TEXT);
356 fprintf(stderr, "mirror write failed\n");
359 case LWS_CALLBACK_RECEIVE:
361 if (ringbuffer[ringbuffer_head].payload)
362 free(ringbuffer[ringbuffer_head].payload);
364 ringbuffer[ringbuffer_head].payload =
365 malloc(LWS_SEND_BUFFER_PRE_PADDING + len +
366 LWS_SEND_BUFFER_POST_PADDING);
367 ringbuffer[ringbuffer_head].len = len;
368 memcpy((char *)ringbuffer[ringbuffer_head].payload +
369 LWS_SEND_BUFFER_PRE_PADDING, in, len);
370 if (ringbuffer_head == (MAX_MESSAGE_QUEUE - 1))
375 if (((ringbuffer_head - pss->ringbuffer_tail) %
376 MAX_MESSAGE_QUEUE) > (MAX_MESSAGE_QUEUE - 10))
377 libwebsocket_rx_flow_control(wsi, 0);
379 libwebsocket_callback_on_writable_all_protocol(
380 libwebsockets_get_protocol(wsi));
384 * this just demonstrates how to use the protocol filter. If you won't
385 * study and reject connections based on header content, you don't need
386 * to handle this callback
389 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
390 dump_handshake_info((struct lws_tokens *)(long)user);
391 /* you could return non-zero here and kill the connection */
402 /* list of supported protocols and callbacks */
404 static struct libwebsocket_protocols protocols[] = {
405 /* first protocol must always be HTTP handler */
408 "http-only", /* name */
409 callback_http, /* callback */
410 0 /* per_session_data_size */
413 "dumb-increment-protocol",
414 callback_dumb_increment,
415 sizeof(struct per_session_data__dumb_increment),
418 "lws-mirror-protocol",
420 sizeof(struct per_session_data__lws_mirror)
423 NULL, NULL, 0 /* End of list */
427 static struct option options[] = {
428 { "help", no_argument, NULL, 'h' },
429 { "debug", required_argument, NULL, 'd' },
430 { "port", required_argument, NULL, 'p' },
431 { "ssl", no_argument, NULL, 's' },
432 { "killmask", no_argument, NULL, 'k' },
433 { "interface", required_argument, NULL, 'i' },
437 int main(int argc, char **argv)
440 const char *cert_path =
441 LOCAL_RESOURCE_PATH"/libwebsockets-test-server.pem";
442 const char *key_path =
443 LOCAL_RESOURCE_PATH"/libwebsockets-test-server.key.pem";
444 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1024 +
445 LWS_SEND_BUFFER_POST_PADDING];
448 struct libwebsocket_context *context;
450 unsigned int oldus = 0;
451 char interface_name[128] = "";
452 const char *interface_ptr = NULL;
454 fprintf(stderr, "libwebsockets test server with external poll()\n"
455 "(C) Copyright 2010-2011 Andy Green <andy@warmcat.com> "
456 "licensed under LGPL2.1\n");
459 n = getopt_long(argc, argv, "i:khsp:d:", options, NULL);
464 lws_set_log_level(atoi(optarg), NULL);
470 opts = LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK;
476 strncpy(interface_name, optarg, sizeof interface_name);
477 interface_name[(sizeof interface_name) - 1] = '\0';
478 interface_ptr = interface_name;
481 fprintf(stderr, "Usage: test-server "
482 "[--port=<p>] [--ssl] "
483 "[-d <log bitfield>]\n");
489 cert_path = key_path = NULL;
491 context = libwebsocket_create_context(port, interface_ptr, protocols,
492 libwebsocket_internal_extensions,
493 cert_path, key_path, NULL, -1, -1,
495 if (context == NULL) {
496 fprintf(stderr, "libwebsocket init failed\n");
500 buf[LWS_SEND_BUFFER_PRE_PADDING] = 'x';
503 * This is an example of an existing application's explicit poll()
504 * loop that libwebsockets can integrate with.
511 * this represents an existing server's single poll action
512 * which also includes libwebsocket sockets
515 n = poll(pollfds, count_pollfds, 25);
520 for (n = 0; n < count_pollfds; n++)
521 if (pollfds[n].revents)
523 * returns immediately if the fd does not
524 * match anything under libwebsockets
527 if (libwebsocket_service_fd(context,
531 /* do our broadcast periodically */
533 gettimeofday(&tv, NULL);
536 * This broadcasts to all dumb-increment-protocol connections
539 * We're just sending a character 'x', in these examples the
540 * callbacks send their own per-connection content.
542 * You have to send something with nonzero length to get the
543 * callback actions delivered.
545 * We take care of pre-and-post padding allocation.
548 if (((unsigned int)tv.tv_usec - oldus) > 50000) {
549 libwebsockets_broadcast(
550 &protocols[PROTOCOL_DUMB_INCREMENT],
551 &buf[LWS_SEND_BUFFER_PRE_PADDING], 1);
557 libwebsocket_context_destroy(context);