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 *wsi,
76 enum libwebsocket_callback_reasons reason, void *user,
80 char client_name[128];
84 case LWS_CALLBACK_HTTP:
85 fprintf(stderr, "serving HTTP URI %s\n", (char *)in);
87 if (in && strcmp(in, "/favicon.ico") == 0) {
88 if (libwebsockets_serve_http_file(wsi,
89 LOCAL_RESOURCE_PATH"/favicon.ico", "image/x-icon"))
90 fprintf(stderr, "Failed to send favicon\n");
94 /* send the script... when it runs it'll start websockets */
96 if (libwebsockets_serve_http_file(wsi,
97 LOCAL_RESOURCE_PATH"/test.html", "text/html"))
98 fprintf(stderr, "Failed to send HTTP file\n");
102 * callback for confirming to continue with client IP appear in
103 * protocol 0 callback since no websocket protocol has been agreed
104 * yet. You can just ignore this if you won't filter on client IP
105 * since the default uhandled callback return is 0 meaning let the
106 * connection continue.
109 case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
111 libwebsockets_get_peer_addresses((int)(long)user, client_name,
112 sizeof(client_name), client_ip, sizeof(client_ip));
114 fprintf(stderr, "Received network connect from %s (%s)\n",
115 client_name, client_ip);
117 /* if we returned non-zero from here, we kill the connection */
121 * callbacks for managing the external poll() array appear in
122 * protocol 0 callback
125 case LWS_CALLBACK_ADD_POLL_FD:
126 pollfds[count_pollfds].fd = (int)(long)user;
127 pollfds[count_pollfds].events = (int)len;
128 pollfds[count_pollfds++].revents = 0;
131 case LWS_CALLBACK_DEL_POLL_FD:
132 for (n = 0; n < count_pollfds; n++)
133 if (pollfds[n].fd == (int)(long)user)
134 while (n < count_pollfds) {
135 pollfds[n] = pollfds[n + 1];
141 case LWS_CALLBACK_SET_MODE_POLL_FD:
142 for (n = 0; n < count_pollfds; n++)
143 if (pollfds[n].fd == (int)(long)user)
144 pollfds[n].events |= (int)(long)len;
147 case LWS_CALLBACK_CLEAR_MODE_POLL_FD:
148 for (n = 0; n < count_pollfds; n++)
149 if (pollfds[n].fd == (int)(long)user)
150 pollfds[n].events &= ~(int)(long)len;
161 * this is just an example of parsing handshake headers, you don't need this
162 * in your code unless you will filter allowing connections by the header
167 dump_handshake_info(struct lws_tokens *lwst)
170 static const char *token_names[] = {
171 [WSI_TOKEN_GET_URI] = "GET URI",
172 [WSI_TOKEN_HOST] = "Host",
173 [WSI_TOKEN_CONNECTION] = "Connection",
174 [WSI_TOKEN_KEY1] = "key 1",
175 [WSI_TOKEN_KEY2] = "key 2",
176 [WSI_TOKEN_PROTOCOL] = "Protocol",
177 [WSI_TOKEN_UPGRADE] = "Upgrade",
178 [WSI_TOKEN_ORIGIN] = "Origin",
179 [WSI_TOKEN_DRAFT] = "Draft",
180 [WSI_TOKEN_CHALLENGE] = "Challenge",
183 [WSI_TOKEN_KEY] = "Key",
184 [WSI_TOKEN_VERSION] = "Version",
185 [WSI_TOKEN_SWORIGIN] = "Sworigin",
188 [WSI_TOKEN_EXTENSIONS] = "Extensions",
190 /* client receives these */
191 [WSI_TOKEN_ACCEPT] = "Accept",
192 [WSI_TOKEN_NONCE] = "Nonce",
193 [WSI_TOKEN_HTTP] = "Http",
196 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
197 if (lwst[n].token == NULL)
200 fprintf(stderr, " %s = %s\n", token_names[n], lwst[n].token);
204 /* dumb_increment protocol */
207 * one of these is auto-created for each connection and a pointer to the
208 * appropriate instance is passed to the callback in the user parameter
210 * for this example protocol we use it to individualize the count for each
214 struct per_session_data__dumb_increment {
219 callback_dumb_increment(struct libwebsocket *wsi,
220 enum libwebsocket_callback_reasons reason,
221 void *user, void *in, size_t len)
224 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 +
225 LWS_SEND_BUFFER_POST_PADDING];
226 unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
227 struct per_session_data__dumb_increment *pss = user;
231 case LWS_CALLBACK_ESTABLISHED:
236 * in this protocol, we just use the broadcast action as the chance to
237 * send our own connection-specific data and ignore the broadcast info
238 * that is available in the 'in' parameter
241 case LWS_CALLBACK_BROADCAST:
242 n = sprintf((char *)p, "%d", pss->number++);
243 n = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
245 fprintf(stderr, "ERROR writing to socket");
250 case LWS_CALLBACK_RECEIVE:
251 fprintf(stderr, "rx %d\n", (int)len);
254 if (strcmp(in, "reset\n") == 0)
259 * this just demonstrates how to use the protocol filter. If you won't
260 * study and reject connections based on header content, you don't need
261 * to handle this callback
264 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
265 dump_handshake_info((struct lws_tokens *)(long)user);
266 /* you could return non-zero here and kill the connection */
277 /* lws-mirror_protocol */
279 #define MAX_MESSAGE_QUEUE 64
281 struct per_session_data__lws_mirror {
282 struct libwebsocket *wsi;
291 static struct a_message ringbuffer[MAX_MESSAGE_QUEUE];
292 static int ringbuffer_head;
296 callback_lws_mirror(struct libwebsocket *wsi,
297 enum libwebsocket_callback_reasons reason,
298 void *user, void *in, size_t len)
301 struct per_session_data__lws_mirror *pss = user;
305 case LWS_CALLBACK_ESTABLISHED:
306 pss->ringbuffer_tail = ringbuffer_head;
308 libwebsocket_callback_on_writable(wsi);
311 case LWS_CALLBACK_CLIENT_WRITEABLE:
313 if (pss->ringbuffer_tail != ringbuffer_head) {
315 n = libwebsocket_write(wsi, (unsigned char *)
316 ringbuffer[pss->ringbuffer_tail].payload +
317 LWS_SEND_BUFFER_PRE_PADDING,
318 ringbuffer[pss->ringbuffer_tail].len,
322 fprintf(stderr, "ERROR writing to socket");
326 if (pss->ringbuffer_tail == (MAX_MESSAGE_QUEUE - 1))
327 pss->ringbuffer_tail = 0;
329 pss->ringbuffer_tail++;
331 if (((ringbuffer_head - pss->ringbuffer_tail) %
332 MAX_MESSAGE_QUEUE) < (MAX_MESSAGE_QUEUE - 15))
333 libwebsocket_rx_flow_control(wsi, 1);
335 libwebsocket_callback_on_writable(wsi);
340 case LWS_CALLBACK_BROADCAST:
341 n = libwebsocket_write(wsi, in, len, LWS_WRITE_TEXT);
343 fprintf(stderr, "mirror write failed\n");
346 case LWS_CALLBACK_RECEIVE:
348 if (ringbuffer[ringbuffer_head].payload)
349 free(ringbuffer[ringbuffer_head].payload);
351 ringbuffer[ringbuffer_head].payload =
352 malloc(LWS_SEND_BUFFER_PRE_PADDING + len +
353 LWS_SEND_BUFFER_POST_PADDING);
354 ringbuffer[ringbuffer_head].len = len;
355 memcpy((char *)ringbuffer[ringbuffer_head].payload +
356 LWS_SEND_BUFFER_PRE_PADDING, in, len);
357 if (ringbuffer_head == (MAX_MESSAGE_QUEUE - 1))
362 if (((ringbuffer_head - pss->ringbuffer_tail) %
363 MAX_MESSAGE_QUEUE) > (MAX_MESSAGE_QUEUE - 10))
364 libwebsocket_rx_flow_control(wsi, 0);
366 libwebsocket_callback_on_writable_all_protocol(
367 libwebsockets_get_protocol(wsi));
371 * this just demonstrates how to use the protocol filter. If you won't
372 * study and reject connections based on header content, you don't need
373 * to handle this callback
376 case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION:
377 dump_handshake_info((struct lws_tokens *)(long)user);
378 /* you could return non-zero here and kill the connection */
389 /* list of supported protocols and callbacks */
391 static struct libwebsocket_protocols protocols[] = {
392 /* first protocol must always be HTTP handler */
395 .callback = callback_http,
397 [PROTOCOL_DUMB_INCREMENT] = {
398 .name = "dumb-increment-protocol",
399 .callback = callback_dumb_increment,
400 .per_session_data_size =
401 sizeof(struct per_session_data__dumb_increment),
403 [PROTOCOL_LWS_MIRROR] = {
404 .name = "lws-mirror-protocol",
405 .callback = callback_lws_mirror,
406 .per_session_data_size =
407 sizeof(struct per_session_data__lws_mirror),
409 [DEMO_PROTOCOL_COUNT] = { /* end of list */
414 static struct option options[] = {
415 { "help", no_argument, NULL, 'h' },
416 { "port", required_argument, NULL, 'p' },
417 { "ssl", no_argument, NULL, 's' },
418 { "killmask", no_argument, NULL, 'k' },
422 int main(int argc, char **argv)
425 const char *cert_path =
426 LOCAL_RESOURCE_PATH"/libwebsockets-test-server.pem";
427 const char *key_path =
428 LOCAL_RESOURCE_PATH"/libwebsockets-test-server.key.pem";
429 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1024 +
430 LWS_SEND_BUFFER_POST_PADDING];
433 struct libwebsocket_context *context;
435 unsigned int oldus = 0;
437 fprintf(stderr, "libwebsockets test server with external poll()\n"
438 "(C) Copyright 2010-2011 Andy Green <andy@warmcat.com> "
439 "licensed under LGPL2.1\n");
442 n = getopt_long(argc, argv, "khsp:", options, NULL);
450 opts = LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK;
456 fprintf(stderr, "Usage: test-server "
457 "[--port=<p>] [--ssl]\n");
463 cert_path = key_path = NULL;
465 context = libwebsocket_create_context(port, protocols, cert_path,
466 key_path, -1, -1, opts);
467 if (context == NULL) {
468 fprintf(stderr, "libwebsocket init failed\n");
472 buf[LWS_SEND_BUFFER_PRE_PADDING] = 'x';
475 * This is an example of an existing application's explicit poll()
476 * loop that libwebsockets can integrate with.
483 * this represents an existing server's single poll action
484 * which also includes libwebsocket sockets
487 n = poll(pollfds, count_pollfds, 25);
492 for (n = 0; n < count_pollfds; n++)
493 if (pollfds[n].revents)
495 * returns immediately if the fd does not
496 * match anything under libwebsockets
499 libwebsocket_service_fd(context,
502 /* do our broadcast periodically */
504 gettimeofday(&tv, NULL);
507 * This broadcasts to all dumb-increment-protocol connections
510 * We're just sending a character 'x', in these examples the
511 * callbacks send their own per-connection content.
513 * You have to send something with nonzero length to get the
514 * callback actions delivered.
516 * We take care of pre-and-post padding allocation.
519 if (((unsigned int)tv.tv_usec - oldus) > 50000) {
520 libwebsockets_broadcast(
521 &protocols[PROTOCOL_DUMB_INCREMENT],
522 &buf[LWS_SEND_BUFFER_PRE_PADDING], 1);
528 libwebsocket_context_destroy(context);