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,
35 #include "../lib/libwebsockets.h"
39 * This demo server shows how to use libwebsockets for one or more
40 * websocket protocols in the same server
42 * It defines the following websocket protocols:
44 * dumb-increment-protocol: once the socket is opened, an incrementing
45 * ascii string is sent down it every 50ms.
46 * If you send "reset\n" on the websocket, then
47 * the incrementing number is reset to 0.
49 * lws-mirror-protocol: copies any received packet to every connection also
50 * using this protocol, including the sender
53 #define MAX_POLL_ELEMENTS 100
54 struct pollfd pollfds[100];
55 int count_pollfds = 0;
63 PROTOCOL_DUMB_INCREMENT,
71 #define LOCAL_RESOURCE_PATH DATADIR"/libwebsockets-test-server"
73 /* this protocol server (always the first one) just knows how to do HTTP */
75 static int callback_http(struct libwebsocket_context * this,
76 struct libwebsocket *wsi,
77 enum libwebsocket_callback_reasons reason, void *user,
81 char client_name[128];
85 case LWS_CALLBACK_HTTP:
86 fprintf(stderr, "serving HTTP URI %s\n", (char *)in);
88 if (in && strcmp(in, "/favicon.ico") == 0) {
89 if (libwebsockets_serve_http_file(wsi,
90 LOCAL_RESOURCE_PATH"/favicon.ico", "image/x-icon"))
91 fprintf(stderr, "Failed to send favicon\n");
95 /* send the script... when it runs it'll start websockets */
97 if (libwebsockets_serve_http_file(wsi,
98 LOCAL_RESOURCE_PATH"/test.html", "text/html"))
99 fprintf(stderr, "Failed to send HTTP file\n");
103 * callback for confirming to continue with client IP appear in
104 * protocol 0 callback since no websocket protocol has been agreed
105 * yet. You can just ignore this if you won't filter on client IP
106 * since the default uhandled callback return is 0 meaning let the
107 * connection continue.
110 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
112 libwebsockets_get_peer_addresses((int)(long)user, client_name,
113 sizeof(client_name), client_ip, sizeof(client_ip));
115 fprintf(stderr, "Received network connect from %s (%s)\n",
116 client_name, client_ip);
118 /* if we returned non-zero from here, we kill the connection */
122 * callbacks for managing the external poll() array appear in
123 * protocol 0 callback
126 case LWS_CALLBACK_ADD_POLL_FD:
127 pollfds[count_pollfds].fd = (int)(long)user;
128 pollfds[count_pollfds].events = (int)len;
129 pollfds[count_pollfds++].revents = 0;
132 case LWS_CALLBACK_DEL_POLL_FD:
133 for (n = 0; n < count_pollfds; n++)
134 if (pollfds[n].fd == (int)(long)user)
135 while (n < count_pollfds) {
136 pollfds[n] = pollfds[n + 1];
142 case LWS_CALLBACK_SET_MODE_POLL_FD:
143 for (n = 0; n < count_pollfds; n++)
144 if (pollfds[n].fd == (int)(long)user)
145 pollfds[n].events |= (int)(long)len;
148 case LWS_CALLBACK_CLEAR_MODE_POLL_FD:
149 for (n = 0; n < count_pollfds; n++)
150 if (pollfds[n].fd == (int)(long)user)
151 pollfds[n].events &= ~(int)(long)len;
162 * this is just an example of parsing handshake headers, you don't need this
163 * in your code unless you will filter allowing connections by the header
168 dump_handshake_info(struct lws_tokens *lwst)
171 static const char *token_names[] = {
172 [WSI_TOKEN_GET_URI] = "GET URI",
173 [WSI_TOKEN_HOST] = "Host",
174 [WSI_TOKEN_CONNECTION] = "Connection",
175 [WSI_TOKEN_KEY1] = "key 1",
176 [WSI_TOKEN_KEY2] = "key 2",
177 [WSI_TOKEN_PROTOCOL] = "Protocol",
178 [WSI_TOKEN_UPGRADE] = "Upgrade",
179 [WSI_TOKEN_ORIGIN] = "Origin",
180 [WSI_TOKEN_DRAFT] = "Draft",
181 [WSI_TOKEN_CHALLENGE] = "Challenge",
184 [WSI_TOKEN_KEY] = "Key",
185 [WSI_TOKEN_VERSION] = "Version",
186 [WSI_TOKEN_SWORIGIN] = "Sworigin",
189 [WSI_TOKEN_EXTENSIONS] = "Extensions",
191 /* client receives these */
192 [WSI_TOKEN_ACCEPT] = "Accept",
193 [WSI_TOKEN_NONCE] = "Nonce",
194 [WSI_TOKEN_HTTP] = "Http",
195 [WSI_TOKEN_MUXURL] = "MuxURL",
198 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
199 if (lwst[n].token == NULL)
202 fprintf(stderr, " %s = %s\n", token_names[n], lwst[n].token);
206 /* dumb_increment protocol */
209 * one of these is auto-created for each connection and a pointer to the
210 * appropriate instance is passed to the callback in the user parameter
212 * for this example protocol we use it to individualize the count for each
216 struct per_session_data__dumb_increment {
221 callback_dumb_increment(struct libwebsocket_context * this,
222 struct libwebsocket *wsi,
223 enum libwebsocket_callback_reasons reason,
224 void *user, void *in, size_t len)
227 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 +
228 LWS_SEND_BUFFER_POST_PADDING];
229 unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
230 struct per_session_data__dumb_increment *pss = user;
234 case LWS_CALLBACK_ESTABLISHED:
239 * in this protocol, we just use the broadcast action as the chance to
240 * send our own connection-specific data and ignore the broadcast info
241 * that is available in the 'in' parameter
244 case LWS_CALLBACK_BROADCAST:
245 n = sprintf((char *)p, "%d", pss->number++);
246 n = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
248 fprintf(stderr, "ERROR writing to socket");
253 case LWS_CALLBACK_RECEIVE:
254 fprintf(stderr, "rx %d\n", (int)len);
257 if (strcmp(in, "reset\n") == 0)
262 * this just demonstrates how to use the protocol filter. If you won't
263 * study and reject connections based on header content, you don't need
264 * to handle this callback
267 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
268 dump_handshake_info((struct lws_tokens *)(long)user);
269 /* you could return non-zero here and kill the connection */
280 /* lws-mirror_protocol */
282 #define MAX_MESSAGE_QUEUE 64
284 struct per_session_data__lws_mirror {
285 struct libwebsocket *wsi;
294 static struct a_message ringbuffer[MAX_MESSAGE_QUEUE];
295 static int ringbuffer_head;
299 callback_lws_mirror(struct libwebsocket_context * this,
300 struct libwebsocket *wsi,
301 enum libwebsocket_callback_reasons reason,
302 void *user, void *in, size_t len)
305 struct per_session_data__lws_mirror *pss = user;
309 case LWS_CALLBACK_ESTABLISHED:
310 pss->ringbuffer_tail = ringbuffer_head;
312 libwebsocket_callback_on_writable(this, wsi);
315 case LWS_CALLBACK_SERVER_WRITEABLE:
317 if (pss->ringbuffer_tail != ringbuffer_head) {
319 n = libwebsocket_write(wsi, (unsigned char *)
320 ringbuffer[pss->ringbuffer_tail].payload +
321 LWS_SEND_BUFFER_PRE_PADDING,
322 ringbuffer[pss->ringbuffer_tail].len,
326 fprintf(stderr, "ERROR writing to socket");
330 if (pss->ringbuffer_tail == (MAX_MESSAGE_QUEUE - 1))
331 pss->ringbuffer_tail = 0;
333 pss->ringbuffer_tail++;
335 if (((ringbuffer_head - pss->ringbuffer_tail) %
336 MAX_MESSAGE_QUEUE) < (MAX_MESSAGE_QUEUE - 15))
337 libwebsocket_rx_flow_control(wsi, 1);
339 libwebsocket_callback_on_writable(this, wsi);
344 case LWS_CALLBACK_BROADCAST:
345 n = libwebsocket_write(wsi, in, len, LWS_WRITE_TEXT);
347 fprintf(stderr, "mirror write failed\n");
350 case LWS_CALLBACK_RECEIVE:
352 if (ringbuffer[ringbuffer_head].payload)
353 free(ringbuffer[ringbuffer_head].payload);
355 ringbuffer[ringbuffer_head].payload =
356 malloc(LWS_SEND_BUFFER_PRE_PADDING + len +
357 LWS_SEND_BUFFER_POST_PADDING);
358 ringbuffer[ringbuffer_head].len = len;
359 memcpy((char *)ringbuffer[ringbuffer_head].payload +
360 LWS_SEND_BUFFER_PRE_PADDING, in, len);
361 if (ringbuffer_head == (MAX_MESSAGE_QUEUE - 1))
366 if (((ringbuffer_head - pss->ringbuffer_tail) %
367 MAX_MESSAGE_QUEUE) > (MAX_MESSAGE_QUEUE - 10))
368 libwebsocket_rx_flow_control(wsi, 0);
370 libwebsocket_callback_on_writable_all_protocol(
371 libwebsockets_get_protocol(wsi));
375 * this just demonstrates how to use the protocol filter. If you won't
376 * study and reject connections based on header content, you don't need
377 * to handle this callback
380 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
381 dump_handshake_info((struct lws_tokens *)(long)user);
382 /* you could return non-zero here and kill the connection */
393 /* list of supported protocols and callbacks */
395 static struct libwebsocket_protocols protocols[] = {
396 /* first protocol must always be HTTP handler */
399 "http-only", /* name */
400 callback_http, /* callback */
401 0 /* per_session_data_size */
404 "dumb-increment-protocol",
405 callback_dumb_increment,
406 sizeof(struct per_session_data__dumb_increment),
409 "lws-mirror-protocol",
411 sizeof(struct per_session_data__lws_mirror)
414 NULL, NULL, 0 /* End of list */
418 static struct option options[] = {
419 { "help", no_argument, NULL, 'h' },
420 { "port", required_argument, NULL, 'p' },
421 { "ssl", no_argument, NULL, 's' },
422 { "killmask", no_argument, NULL, 'k' },
423 { "interface", required_argument, NULL, 'i' },
427 int main(int argc, char **argv)
430 const char *cert_path =
431 LOCAL_RESOURCE_PATH"/libwebsockets-test-server.pem";
432 const char *key_path =
433 LOCAL_RESOURCE_PATH"/libwebsockets-test-server.key.pem";
434 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1024 +
435 LWS_SEND_BUFFER_POST_PADDING];
438 struct libwebsocket_context *context;
440 unsigned int oldus = 0;
441 char interface_name[128] = "";
442 const char * interface = NULL;
444 fprintf(stderr, "libwebsockets test server with external poll()\n"
445 "(C) Copyright 2010-2011 Andy Green <andy@warmcat.com> "
446 "licensed under LGPL2.1\n");
449 n = getopt_long(argc, argv, "i:khsp:", options, NULL);
457 opts = LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK;
463 strncpy(interface_name, optarg, sizeof interface_name);
464 interface_name[(sizeof interface_name) - 1] = '\0';
465 interface = interface_name;
468 fprintf(stderr, "Usage: test-server "
469 "[--port=<p>] [--ssl]\n");
475 cert_path = key_path = NULL;
477 context = libwebsocket_create_context(port, interface, protocols,
478 libwebsocket_internal_extensions,
479 cert_path, key_path, -1, -1, opts);
480 if (context == NULL) {
481 fprintf(stderr, "libwebsocket init failed\n");
485 buf[LWS_SEND_BUFFER_PRE_PADDING] = 'x';
488 * This is an example of an existing application's explicit poll()
489 * loop that libwebsockets can integrate with.
496 * this represents an existing server's single poll action
497 * which also includes libwebsocket sockets
500 n = poll(pollfds, count_pollfds, 25);
505 for (n = 0; n < count_pollfds; n++)
506 if (pollfds[n].revents)
508 * returns immediately if the fd does not
509 * match anything under libwebsockets
512 libwebsocket_service_fd(context,
515 /* do our broadcast periodically */
517 gettimeofday(&tv, NULL);
520 * This broadcasts to all dumb-increment-protocol connections
523 * We're just sending a character 'x', in these examples the
524 * callbacks send their own per-connection content.
526 * You have to send something with nonzero length to get the
527 * callback actions delivered.
529 * We take care of pre-and-post padding allocation.
532 if (((unsigned int)tv.tv_usec - oldus) > 50000) {
533 libwebsockets_broadcast(
534 &protocols[PROTOCOL_DUMB_INCREMENT],
535 &buf[LWS_SEND_BUFFER_PRE_PADDING], 1);
541 libwebsocket_context_destroy(context);