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",
197 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
198 if (lwst[n].token == NULL)
201 fprintf(stderr, " %s = %s\n", token_names[n], lwst[n].token);
205 /* dumb_increment protocol */
208 * one of these is auto-created for each connection and a pointer to the
209 * appropriate instance is passed to the callback in the user parameter
211 * for this example protocol we use it to individualize the count for each
215 struct per_session_data__dumb_increment {
220 callback_dumb_increment(struct libwebsocket_context * this,
221 struct libwebsocket *wsi,
222 enum libwebsocket_callback_reasons reason,
223 void *user, void *in, size_t len)
226 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 +
227 LWS_SEND_BUFFER_POST_PADDING];
228 unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
229 struct per_session_data__dumb_increment *pss = user;
233 case LWS_CALLBACK_ESTABLISHED:
238 * in this protocol, we just use the broadcast action as the chance to
239 * send our own connection-specific data and ignore the broadcast info
240 * that is available in the 'in' parameter
243 case LWS_CALLBACK_BROADCAST:
244 n = sprintf((char *)p, "%d", pss->number++);
245 n = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
247 fprintf(stderr, "ERROR writing to socket");
252 case LWS_CALLBACK_RECEIVE:
253 fprintf(stderr, "rx %d\n", (int)len);
256 if (strcmp(in, "reset\n") == 0)
261 * this just demonstrates how to use the protocol filter. If you won't
262 * study and reject connections based on header content, you don't need
263 * to handle this callback
266 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
267 dump_handshake_info((struct lws_tokens *)(long)user);
268 /* you could return non-zero here and kill the connection */
279 /* lws-mirror_protocol */
281 #define MAX_MESSAGE_QUEUE 64
283 struct per_session_data__lws_mirror {
284 struct libwebsocket *wsi;
293 static struct a_message ringbuffer[MAX_MESSAGE_QUEUE];
294 static int ringbuffer_head;
298 callback_lws_mirror(struct libwebsocket_context * this,
299 struct libwebsocket *wsi,
300 enum libwebsocket_callback_reasons reason,
301 void *user, void *in, size_t len)
304 struct per_session_data__lws_mirror *pss = user;
308 case LWS_CALLBACK_ESTABLISHED:
309 pss->ringbuffer_tail = ringbuffer_head;
311 libwebsocket_callback_on_writable(this, wsi);
314 case LWS_CALLBACK_CLIENT_WRITEABLE:
316 if (pss->ringbuffer_tail != ringbuffer_head) {
318 n = libwebsocket_write(wsi, (unsigned char *)
319 ringbuffer[pss->ringbuffer_tail].payload +
320 LWS_SEND_BUFFER_PRE_PADDING,
321 ringbuffer[pss->ringbuffer_tail].len,
325 fprintf(stderr, "ERROR writing to socket");
329 if (pss->ringbuffer_tail == (MAX_MESSAGE_QUEUE - 1))
330 pss->ringbuffer_tail = 0;
332 pss->ringbuffer_tail++;
334 if (((ringbuffer_head - pss->ringbuffer_tail) %
335 MAX_MESSAGE_QUEUE) < (MAX_MESSAGE_QUEUE - 15))
336 libwebsocket_rx_flow_control(wsi, 1);
338 libwebsocket_callback_on_writable(this, wsi);
343 case LWS_CALLBACK_BROADCAST:
344 n = libwebsocket_write(wsi, in, len, LWS_WRITE_TEXT);
346 fprintf(stderr, "mirror write failed\n");
349 case LWS_CALLBACK_RECEIVE:
351 if (ringbuffer[ringbuffer_head].payload)
352 free(ringbuffer[ringbuffer_head].payload);
354 ringbuffer[ringbuffer_head].payload =
355 malloc(LWS_SEND_BUFFER_PRE_PADDING + len +
356 LWS_SEND_BUFFER_POST_PADDING);
357 ringbuffer[ringbuffer_head].len = len;
358 memcpy((char *)ringbuffer[ringbuffer_head].payload +
359 LWS_SEND_BUFFER_PRE_PADDING, in, len);
360 if (ringbuffer_head == (MAX_MESSAGE_QUEUE - 1))
365 if (((ringbuffer_head - pss->ringbuffer_tail) %
366 MAX_MESSAGE_QUEUE) > (MAX_MESSAGE_QUEUE - 10))
367 libwebsocket_rx_flow_control(wsi, 0);
369 libwebsocket_callback_on_writable_all_protocol(
370 libwebsockets_get_protocol(wsi));
374 * this just demonstrates how to use the protocol filter. If you won't
375 * study and reject connections based on header content, you don't need
376 * to handle this callback
379 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
380 dump_handshake_info((struct lws_tokens *)(long)user);
381 /* you could return non-zero here and kill the connection */
392 /* list of supported protocols and callbacks */
394 static struct libwebsocket_protocols protocols[] = {
395 /* first protocol must always be HTTP handler */
398 .callback = callback_http,
400 [PROTOCOL_DUMB_INCREMENT] = {
401 .name = "dumb-increment-protocol",
402 .callback = callback_dumb_increment,
403 .per_session_data_size =
404 sizeof(struct per_session_data__dumb_increment),
406 [PROTOCOL_LWS_MIRROR] = {
407 .name = "lws-mirror-protocol",
408 .callback = callback_lws_mirror,
409 .per_session_data_size =
410 sizeof(struct per_session_data__lws_mirror),
412 [DEMO_PROTOCOL_COUNT] = { /* end of list */
417 static struct option options[] = {
418 { "help", no_argument, NULL, 'h' },
419 { "port", required_argument, NULL, 'p' },
420 { "ssl", no_argument, NULL, 's' },
421 { "killmask", no_argument, NULL, 'k' },
425 int main(int argc, char **argv)
428 const char *cert_path =
429 LOCAL_RESOURCE_PATH"/libwebsockets-test-server.pem";
430 const char *key_path =
431 LOCAL_RESOURCE_PATH"/libwebsockets-test-server.key.pem";
432 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1024 +
433 LWS_SEND_BUFFER_POST_PADDING];
436 struct libwebsocket_context *context;
438 unsigned int oldus = 0;
440 fprintf(stderr, "libwebsockets test server with external poll()\n"
441 "(C) Copyright 2010-2011 Andy Green <andy@warmcat.com> "
442 "licensed under LGPL2.1\n");
445 n = getopt_long(argc, argv, "khsp:", options, NULL);
453 opts = LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK;
459 fprintf(stderr, "Usage: test-server "
460 "[--port=<p>] [--ssl]\n");
466 cert_path = key_path = NULL;
468 context = libwebsocket_create_context(port, protocols, cert_path,
469 key_path, -1, -1, opts);
470 if (context == NULL) {
471 fprintf(stderr, "libwebsocket init failed\n");
475 buf[LWS_SEND_BUFFER_PRE_PADDING] = 'x';
478 * This is an example of an existing application's explicit poll()
479 * loop that libwebsockets can integrate with.
486 * this represents an existing server's single poll action
487 * which also includes libwebsocket sockets
490 n = poll(pollfds, count_pollfds, 25);
495 for (n = 0; n < count_pollfds; n++)
496 if (pollfds[n].revents)
498 * returns immediately if the fd does not
499 * match anything under libwebsockets
502 libwebsocket_service_fd(context,
505 /* do our broadcast periodically */
507 gettimeofday(&tv, NULL);
510 * This broadcasts to all dumb-increment-protocol connections
513 * We're just sending a character 'x', in these examples the
514 * callbacks send their own per-connection content.
516 * You have to send something with nonzero length to get the
517 * callback actions delivered.
519 * We take care of pre-and-post padding allocation.
522 if (((unsigned int)tv.tv_usec - oldus) > 50000) {
523 libwebsockets_broadcast(
524 &protocols[PROTOCOL_DUMB_INCREMENT],
525 &buf[LWS_SEND_BUFFER_PRE_PADDING], 1);
531 libwebsocket_context_destroy(context);