2012-09-19 19:31:19 +08:00
|
|
|
// Copyright (c) 2004-2012 Sergey Lyubka
|
|
|
|
// This file is a part of mongoose project, http://github.com/valenok/mongoose
|
|
|
|
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <string.h>
|
2013-09-30 05:01:31 +08:00
|
|
|
#include <stdlib.h>
|
2012-09-19 19:31:19 +08:00
|
|
|
#include "mongoose.h"
|
|
|
|
|
2013-09-28 18:00:54 +08:00
|
|
|
static int event_handler(struct mg_event *event) {
|
|
|
|
|
|
|
|
if (event->type == MG_REQUEST_BEGIN) {
|
|
|
|
const char *version_header = mg_get_header(event->conn,
|
|
|
|
"Sec-WebSocket-Version");
|
|
|
|
|
|
|
|
if (version_header != NULL) {
|
|
|
|
// Websocket request, process it
|
|
|
|
if (strcmp(version_header, "13") != 0) {
|
|
|
|
mg_printf(event->conn, "%s", "HTTP/1.1 426 Upgrade Required\r\n\r\n");
|
|
|
|
} else {
|
|
|
|
static const char *server_ready_message = "server ready";
|
|
|
|
char *data;
|
|
|
|
int bits, len;
|
2013-02-02 00:48:30 +08:00
|
|
|
|
2013-09-28 18:00:54 +08:00
|
|
|
// Handshake, and send initial server message
|
|
|
|
mg_websocket_handshake(event->conn);
|
|
|
|
mg_websocket_write(event->conn, WEBSOCKET_OPCODE_TEXT,
|
|
|
|
server_ready_message, strlen(server_ready_message));
|
|
|
|
|
2013-09-30 05:01:31 +08:00
|
|
|
// Read messages sent by client. Echo them back.
|
2013-09-28 18:00:54 +08:00
|
|
|
while ((len = mg_websocket_read(event->conn, &bits, &data)) > 0) {
|
2013-09-29 16:25:47 +08:00
|
|
|
printf("got message: [%.*s]\n", len, data);
|
2013-09-30 05:01:31 +08:00
|
|
|
mg_websocket_write(event->conn, WEBSOCKET_OPCODE_TEXT, data, len);
|
|
|
|
free(data); // It's our responsibility to free allocated message
|
|
|
|
|
|
|
|
// If the message is "exit", close the connection, exit the loop
|
2013-09-28 18:00:54 +08:00
|
|
|
if (memcmp(data, "exit", 4) == 0) {
|
|
|
|
mg_websocket_write(event->conn,
|
|
|
|
WEBSOCKET_OPCODE_CONNECTION_CLOSE, "", 0);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
2012-09-19 19:31:19 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
int main(void) {
|
|
|
|
struct mg_context *ctx;
|
|
|
|
const char *options[] = {
|
|
|
|
"listening_ports", "8080",
|
|
|
|
"document_root", "websocket_html_root",
|
|
|
|
NULL
|
|
|
|
};
|
|
|
|
|
2013-09-28 18:00:54 +08:00
|
|
|
ctx = mg_start(options, &event_handler, NULL);
|
2012-09-19 19:31:19 +08:00
|
|
|
getchar(); // Wait until user hits "enter"
|
|
|
|
mg_stop(ctx);
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|