2014-01-17 11:45:57 +00:00
|
|
|
#include <string.h>
|
2012-09-19 12:31:19 +01:00
|
|
|
#include "mongoose.h"
|
|
|
|
|
2014-01-17 10:17:15 +00:00
|
|
|
extern const char *find_embedded_file(const char *, size_t *);
|
2013-09-29 22:43:58 +01:00
|
|
|
|
2014-01-17 11:45:57 +00:00
|
|
|
static int iterate_callback(struct mg_connection *c) {
|
2014-01-17 10:17:15 +00:00
|
|
|
if (c->is_websocket) {
|
|
|
|
char buf[20];
|
2014-01-17 11:45:57 +00:00
|
|
|
int len = snprintf(buf, sizeof(buf), "%d", * (int *) c->connection_param);
|
2014-01-17 10:17:15 +00:00
|
|
|
mg_websocket_write(c, 1, buf, len);
|
2013-09-28 11:00:54 +01:00
|
|
|
}
|
2014-01-17 11:45:57 +00:00
|
|
|
return 1;
|
2014-01-17 10:17:15 +00:00
|
|
|
}
|
2013-09-28 11:00:54 +01:00
|
|
|
|
2014-01-17 10:17:15 +00:00
|
|
|
static int index_html(struct mg_connection *conn) {
|
|
|
|
size_t index_size;
|
|
|
|
const char *index_html = find_embedded_file("websocket.html", &index_size);
|
|
|
|
|
|
|
|
if (conn->is_websocket) {
|
2014-01-17 16:37:05 +00:00
|
|
|
// This handler is called for each incoming websocket frame, one or more
|
|
|
|
// times for connection lifetime.
|
|
|
|
// Echo websocket data back to the client.
|
2014-01-17 10:17:15 +00:00
|
|
|
mg_websocket_write(conn, 1, conn->content, conn->content_len);
|
|
|
|
return conn->content_len == 4 && !memcmp(conn->content, "exit", 4);
|
|
|
|
} else {
|
|
|
|
mg_send_header(conn, "Content-Type", "text/html");
|
|
|
|
mg_send_data(conn, index_html, index_size);
|
|
|
|
return 1;
|
|
|
|
}
|
2012-09-19 12:31:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
int main(void) {
|
2014-01-17 10:17:15 +00:00
|
|
|
struct mg_server *server = mg_create_server(NULL);
|
|
|
|
unsigned int current_timer = 0, last_timer = 0;
|
|
|
|
|
|
|
|
mg_set_option(server, "listening_port", "8080");
|
|
|
|
mg_add_uri_handler(server, "/", index_html);
|
|
|
|
|
|
|
|
printf("Started on port %s\n", mg_get_option(server, "listening_port"));
|
|
|
|
for (;;) {
|
|
|
|
current_timer = mg_poll_server(server, 100);
|
2014-01-17 16:37:05 +00:00
|
|
|
if (current_timer - last_timer > 1) {
|
2014-01-17 10:17:15 +00:00
|
|
|
last_timer = current_timer;
|
|
|
|
mg_iterate_over_connections(server, iterate_callback, ¤t_timer);
|
|
|
|
}
|
|
|
|
}
|
2012-09-19 12:31:19 +01:00
|
|
|
|
2014-01-17 10:17:15 +00:00
|
|
|
mg_destroy_server(&server);
|
2012-09-19 12:31:19 +01:00
|
|
|
return 0;
|
|
|
|
}
|