7 #include "libwebsockets.h"
10 * libwebsocket Example server Copyright 2010 Andy Green <andy@warmcat.com>
12 * Shows how to use libwebsocket
15 static int port = 7681;
16 static int ws_protocol = 76;
19 * libwebsockets needs this one callback in your server application, it's
20 * called for a handful of different reasons during the connection lifecycle.
22 * All the serving actions occur in the callback but the websocket protocol
23 * stuff is already handled by the library.
26 static int websocket_callback(struct libwebsocket * wsi,
27 enum libwebsocket_callback_reasons reason, void *in, size_t len)
30 char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 +
31 LWS_SEND_BUFFER_POST_PADDING];
33 char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
38 * Websockets session handshake completed and is established
40 case LWS_CALLBACK_ESTABLISHED:
41 fprintf(stderr, "Websocket connection established\n");
45 * Websockets session is closed
47 case LWS_CALLBACK_CLOSED:
48 fprintf(stderr, "Websocket connection closed\n");
52 * Opportunity for us to send something on the connection
54 case LWS_CALLBACK_SEND:
55 n = sprintf(p, "%d", bump++);
56 n = libwebsocket_write(wsi, (unsigned char *)p, n, 0);
58 fprintf(stderr, "ERROR writing to socket");
63 * Something has arrived for us on the connection, it's len bytes long
64 * and is available at *in
66 case LWS_CALLBACK_RECEIVE:
67 fprintf(stderr, "Received %d bytes payload\n", (int)len);
71 * The client has asked us for something in normal HTTP mode,
72 * not websockets mode. Normally it means we want to send
73 * our script / html to the client, and when that script runs
74 * it will start up separate websocket connections.
76 * Interpret the URI string to figure out what is needed to send
79 case LWS_CALLBACK_HTTP:
81 uri = libwebsocket_get_uri(wsi);
82 if (uri && strcmp(uri, "/favicon.ico") == 0) {
83 if (libwebsockets_serve_http_file(wsi, "./favicon.ico",
85 fprintf(stderr, "Failed to send favicon\n");
89 /* send the script... when it runs it'll start websockets */
91 if (libwebsockets_serve_http_file(wsi, "./test.html",
93 fprintf(stderr, "Failed to send HTTP file\n");
101 static struct option options[] = {
102 { "help", no_argument, NULL, 'h' },
103 { "port", required_argument, NULL, 'p' },
104 { "protocol", required_argument, NULL, 'r' },
108 int main(int argc, char **argv)
112 fprintf(stderr, "libwebsockets test server\n"
113 "Copyright 2010 Andy Green <andy@warmcat.com> "
114 "licensed under GPL2\n");
117 n = getopt_long(argc, argv, "hp:r:", options, NULL);
125 ws_protocol = atoi(optarg);
128 fprintf(stderr, "Usage: test-server "
129 "[--port=<p>] [--protocol=<v>]\n");
134 if (libwebsocket_create_server(port, websocket_callback, ws_protocol) <
136 fprintf(stderr, "libwebsocket init failed\n");
140 /* just sit there until killed */