websocket_echo_server.c
Go to the documentation of this file.
00001 // Copyright (c) 2013-2014 Cesanta Software Limited
00002 // $Date: 2014-09-09 17:07:55 UTC $
00003 
00004 #include <string.h>
00005 #include <time.h>
00006 #include "mongoose.h"
00007 
00008 static void push_message(struct mg_server *server, time_t current_time) {
00009   struct mg_connection *c;
00010   char buf[20];
00011   int len = sprintf(buf, "%lu", (unsigned long) current_time);
00012 
00013   // Iterate over all connections, and push current time message to websocket ones.
00014   for (c = mg_next(server, NULL); c != NULL; c = mg_next(server, c)) {
00015     if (c->is_websocket) {
00016       mg_websocket_write(c, 1, buf, len);
00017     }
00018   }
00019 }
00020 
00021 static int send_reply(struct mg_connection *conn) {
00022   if (conn->is_websocket) {
00023     // This handler is called for each incoming websocket frame, one or more
00024     // times for connection lifetime.
00025     // Echo websocket data back to the client.
00026     mg_websocket_write(conn, 1, conn->content, conn->content_len);
00027     return conn->content_len == 4 && !memcmp(conn->content, "exit", 4) ?
00028       MG_FALSE : MG_TRUE;
00029   } else {
00030     mg_send_file(conn, "index.html", NULL);
00031     return MG_MORE;
00032   }
00033 }
00034 
00035 static int ev_handler(struct mg_connection *conn, enum mg_event ev) {
00036   switch (ev) {
00037     case MG_AUTH: return MG_TRUE;
00038     case MG_REQUEST: return send_reply(conn);
00039     default: return MG_FALSE;
00040   }
00041 }
00042 
00043 int main(void) {
00044   struct mg_server *server = mg_create_server(NULL, ev_handler);
00045   time_t current_timer = 0, last_timer = time(NULL);
00046 
00047   mg_set_option(server, "listening_port", "8080");
00048 
00049   printf("Started on port %s\n", mg_get_option(server, "listening_port"));
00050   for (;;) {
00051     mg_poll_server(server, 100);
00052     current_timer = time(NULL);
00053     if (current_timer - last_timer > 0) {
00054       last_timer = current_timer;
00055       push_message(server, current_timer);
00056     }
00057   }
00058 
00059   mg_destroy_server(&server);
00060   return 0;
00061 }


rc_visard_driver
Author(s): Heiko Hirschmueller , Christian Emmerich , Felix Ruess
autogenerated on Thu Jun 6 2019 20:43:07