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");
111 * callback for confirming to continue with client IP appear in
112 * protocol 0 callback since no websocket protocol has been agreed
113 * yet. You can just ignore this if you won't filter on client IP
114 * since the default uhandled callback return is 0 meaning let the
115 * connection continue.
118 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
120 libwebsockets_get_peer_addresses((int)(long)user, client_name,
121 sizeof(client_name), client_ip, sizeof(client_ip));
123 fprintf(stderr, "Received network connect from %s (%s)\n",
124 client_name, client_ip);
126 /* if we returned non-zero from here, we kill the connection */
130 * callbacks for managing the external poll() array appear in
131 * protocol 0 callback
134 case LWS_CALLBACK_ADD_POLL_FD:
135 pollfds[count_pollfds].fd = (int)(long)user;
136 pollfds[count_pollfds].events = (int)len;
137 pollfds[count_pollfds++].revents = 0;
140 case LWS_CALLBACK_DEL_POLL_FD:
141 for (n = 0; n < count_pollfds; n++)
142 if (pollfds[n].fd == (int)(long)user)
143 while (n < count_pollfds) {
144 pollfds[n] = pollfds[n + 1];
150 case LWS_CALLBACK_SET_MODE_POLL_FD:
151 for (n = 0; n < count_pollfds; n++)
152 if (pollfds[n].fd == (int)(long)user)
153 pollfds[n].events |= (int)(long)len;
156 case LWS_CALLBACK_CLEAR_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;
170 * this is just an example of parsing handshake headers, you don't need this
171 * in your code unless you will filter allowing connections by the header
176 dump_handshake_info(struct lws_tokens *lwst)
179 static const char *token_names[] = {
180 [WSI_TOKEN_GET_URI] = "GET URI",
181 [WSI_TOKEN_HOST] = "Host",
182 [WSI_TOKEN_CONNECTION] = "Connection",
183 [WSI_TOKEN_KEY1] = "key 1",
184 [WSI_TOKEN_KEY2] = "key 2",
185 [WSI_TOKEN_PROTOCOL] = "Protocol",
186 [WSI_TOKEN_UPGRADE] = "Upgrade",
187 [WSI_TOKEN_ORIGIN] = "Origin",
188 [WSI_TOKEN_DRAFT] = "Draft",
189 [WSI_TOKEN_CHALLENGE] = "Challenge",
192 [WSI_TOKEN_KEY] = "Key",
193 [WSI_TOKEN_VERSION] = "Version",
194 [WSI_TOKEN_SWORIGIN] = "Sworigin",
197 [WSI_TOKEN_EXTENSIONS] = "Extensions",
199 /* client receives these */
200 [WSI_TOKEN_ACCEPT] = "Accept",
201 [WSI_TOKEN_NONCE] = "Nonce",
202 [WSI_TOKEN_HTTP] = "Http",
203 [WSI_TOKEN_MUXURL] = "MuxURL",
206 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
207 if (lwst[n].token == NULL)
210 fprintf(stderr, " %s = %s\n", token_names[n], lwst[n].token);
214 /* dumb_increment protocol */
217 * one of these is auto-created for each connection and a pointer to the
218 * appropriate instance is passed to the callback in the user parameter
220 * for this example protocol we use it to individualize the count for each
224 struct per_session_data__dumb_increment {
229 callback_dumb_increment(struct libwebsocket_context * this,
230 struct libwebsocket *wsi,
231 enum libwebsocket_callback_reasons reason,
232 void *user, void *in, size_t len)
235 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 +
236 LWS_SEND_BUFFER_POST_PADDING];
237 unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
238 struct per_session_data__dumb_increment *pss = user;
242 case LWS_CALLBACK_ESTABLISHED:
247 * in this protocol, we just use the broadcast action as the chance to
248 * send our own connection-specific data and ignore the broadcast info
249 * that is available in the 'in' parameter
252 case LWS_CALLBACK_BROADCAST:
253 n = sprintf((char *)p, "%d", pss->number++);
254 n = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
256 fprintf(stderr, "ERROR writing to socket");
261 case LWS_CALLBACK_RECEIVE:
262 fprintf(stderr, "rx %d\n", (int)len);
265 if (strcmp(in, "reset\n") == 0)
270 * this just demonstrates how to use the protocol filter. If you won't
271 * study and reject connections based on header content, you don't need
272 * to handle this callback
275 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
276 dump_handshake_info((struct lws_tokens *)(long)user);
277 /* you could return non-zero here and kill the connection */
288 /* lws-mirror_protocol */
290 #define MAX_MESSAGE_QUEUE 64
292 struct per_session_data__lws_mirror {
293 struct libwebsocket *wsi;
302 static struct a_message ringbuffer[MAX_MESSAGE_QUEUE];
303 static int ringbuffer_head;
307 callback_lws_mirror(struct libwebsocket_context * this,
308 struct libwebsocket *wsi,
309 enum libwebsocket_callback_reasons reason,
310 void *user, void *in, size_t len)
313 struct per_session_data__lws_mirror *pss = user;
317 case LWS_CALLBACK_ESTABLISHED:
318 pss->ringbuffer_tail = ringbuffer_head;
320 libwebsocket_callback_on_writable(this, wsi);
323 case LWS_CALLBACK_SERVER_WRITEABLE:
325 if (pss->ringbuffer_tail != ringbuffer_head) {
327 n = libwebsocket_write(wsi, (unsigned char *)
328 ringbuffer[pss->ringbuffer_tail].payload +
329 LWS_SEND_BUFFER_PRE_PADDING,
330 ringbuffer[pss->ringbuffer_tail].len,
334 fprintf(stderr, "ERROR writing to socket");
338 if (pss->ringbuffer_tail == (MAX_MESSAGE_QUEUE - 1))
339 pss->ringbuffer_tail = 0;
341 pss->ringbuffer_tail++;
343 if (((ringbuffer_head - pss->ringbuffer_tail) %
344 MAX_MESSAGE_QUEUE) < (MAX_MESSAGE_QUEUE - 15))
345 libwebsocket_rx_flow_control(wsi, 1);
347 libwebsocket_callback_on_writable(this, wsi);
352 case LWS_CALLBACK_BROADCAST:
353 n = libwebsocket_write(wsi, in, len, LWS_WRITE_TEXT);
355 fprintf(stderr, "mirror write failed\n");
358 case LWS_CALLBACK_RECEIVE:
360 if (ringbuffer[ringbuffer_head].payload)
361 free(ringbuffer[ringbuffer_head].payload);
363 ringbuffer[ringbuffer_head].payload =
364 malloc(LWS_SEND_BUFFER_PRE_PADDING + len +
365 LWS_SEND_BUFFER_POST_PADDING);
366 ringbuffer[ringbuffer_head].len = len;
367 memcpy((char *)ringbuffer[ringbuffer_head].payload +
368 LWS_SEND_BUFFER_PRE_PADDING, in, len);
369 if (ringbuffer_head == (MAX_MESSAGE_QUEUE - 1))
374 if (((ringbuffer_head - pss->ringbuffer_tail) %
375 MAX_MESSAGE_QUEUE) > (MAX_MESSAGE_QUEUE - 10))
376 libwebsocket_rx_flow_control(wsi, 0);
378 libwebsocket_callback_on_writable_all_protocol(
379 libwebsockets_get_protocol(wsi));
383 * this just demonstrates how to use the protocol filter. If you won't
384 * study and reject connections based on header content, you don't need
385 * to handle this callback
388 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
389 dump_handshake_info((struct lws_tokens *)(long)user);
390 /* you could return non-zero here and kill the connection */
401 /* list of supported protocols and callbacks */
403 static struct libwebsocket_protocols protocols[] = {
404 /* first protocol must always be HTTP handler */
407 "http-only", /* name */
408 callback_http, /* callback */
409 0 /* per_session_data_size */
412 "dumb-increment-protocol",
413 callback_dumb_increment,
414 sizeof(struct per_session_data__dumb_increment),
417 "lws-mirror-protocol",
419 sizeof(struct per_session_data__lws_mirror)
422 NULL, NULL, 0 /* End of list */
426 static struct option options[] = {
427 { "help", no_argument, NULL, 'h' },
428 { "port", required_argument, NULL, 'p' },
429 { "ssl", no_argument, NULL, 's' },
430 { "killmask", no_argument, NULL, 'k' },
431 { "interface", required_argument, NULL, 'i' },
435 int main(int argc, char **argv)
438 const char *cert_path =
439 LOCAL_RESOURCE_PATH"/libwebsockets-test-server.pem";
440 const char *key_path =
441 LOCAL_RESOURCE_PATH"/libwebsockets-test-server.key.pem";
442 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1024 +
443 LWS_SEND_BUFFER_POST_PADDING];
446 struct libwebsocket_context *context;
448 unsigned int oldus = 0;
449 char interface_name[128] = "";
450 const char *interface_ptr = NULL;
452 fprintf(stderr, "libwebsockets test server with external poll()\n"
453 "(C) Copyright 2010-2011 Andy Green <andy@warmcat.com> "
454 "licensed under LGPL2.1\n");
457 n = getopt_long(argc, argv, "i:khsp:", options, NULL);
465 opts = LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK;
471 strncpy(interface_name, optarg, sizeof interface_name);
472 interface_name[(sizeof interface_name) - 1] = '\0';
473 interface_ptr = interface_name;
476 fprintf(stderr, "Usage: test-server "
477 "[--port=<p>] [--ssl]\n");
483 cert_path = key_path = NULL;
485 context = libwebsocket_create_context(port, interface_ptr, protocols,
486 libwebsocket_internal_extensions,
487 cert_path, key_path, -1, -1, opts, NULL);
488 if (context == NULL) {
489 fprintf(stderr, "libwebsocket init failed\n");
493 buf[LWS_SEND_BUFFER_PRE_PADDING] = 'x';
496 * This is an example of an existing application's explicit poll()
497 * loop that libwebsockets can integrate with.
504 * this represents an existing server's single poll action
505 * which also includes libwebsocket sockets
508 n = poll(pollfds, count_pollfds, 25);
513 for (n = 0; n < count_pollfds; n++)
514 if (pollfds[n].revents)
516 * returns immediately if the fd does not
517 * match anything under libwebsockets
520 if (libwebsocket_service_fd(context,
524 /* do our broadcast periodically */
526 gettimeofday(&tv, NULL);
529 * This broadcasts to all dumb-increment-protocol connections
532 * We're just sending a character 'x', in these examples the
533 * callbacks send their own per-connection content.
535 * You have to send something with nonzero length to get the
536 * callback actions delivered.
538 * We take care of pre-and-post padding allocation.
541 if (((unsigned int)tv.tv_usec - oldus) > 50000) {
542 libwebsockets_broadcast(
543 &protocols[PROTOCOL_DUMB_INCREMENT],
544 &buf[LWS_SEND_BUFFER_PRE_PADDING], 1);
550 libwebsocket_context_destroy(context);