Statistics
| Branch: | Tag: | Revision:

mongoose / examples / websocket_chat / websocket_chat.c @ eaef5bd1

History | View | Annotate | Download (2.11 KB)

1
/*
2
 * Copyright (c) 2014 Cesanta Software Limited
3
 * All rights reserved
4
 */
5

    
6
#include "mongoose.h"
7

    
8
static sig_atomic_t s_signal_received = 0;
9
static const char *s_http_port = "8000";
10

    
11
static void signal_handler(int sig_num) {
12
  signal(sig_num, signal_handler);  // Reinstantiate signal handler
13
  s_signal_received = sig_num;
14
}
15

    
16
static int is_websocket(const struct mg_connection *nc) {
17
  return nc->flags & MG_F_IS_WEBSOCKET;
18
}
19

    
20
static void broadcast(struct mg_connection *nc, const struct mg_str msg) {
21
  struct mg_connection *c;
22
  char buf[500];
23
  char addr[32];
24
  mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr),
25
                      MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
26

    
27
  snprintf(buf, sizeof(buf), "%s %.*s", addr, (int) msg.len, msg.p);
28
  printf("%s\n", buf); /* Local echo. */
29
  for (c = mg_next(nc->mgr, NULL); c != NULL; c = mg_next(nc->mgr, c)) {
30
    if (c == nc) continue; /* Don't send to the sender. */
31
    mg_send_websocket_frame(c, WEBSOCKET_OP_TEXT, buf, strlen(buf));
32
  }
33
}
34

    
35
static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
36
  switch (ev) {
37
    case MG_EV_WEBSOCKET_HANDSHAKE_DONE: {
38
      /* New websocket connection. Tell everybody. */
39
      broadcast(nc, mg_mk_str("++ joined"));
40
      break;
41
    }
42
    case MG_EV_WEBSOCKET_FRAME: {
43
      struct websocket_message *wm = (struct websocket_message *) ev_data;
44
      /* New websocket message. Tell everybody. */
45
      struct mg_str d = {(char *) wm->data, wm->size};
46
      broadcast(nc, d);
47
      break;
48
    }
49
    case MG_EV_CLOSE: {
50
      /* Disconnect. Tell everybody. */
51
      if (is_websocket(nc)) {
52
        broadcast(nc, mg_mk_str("-- left"));
53
      }
54
      break;
55
    }
56
  }
57
}
58

    
59
int main(void) {
60
  struct mg_mgr mgr;
61
  struct mg_connection *nc;
62

    
63
  signal(SIGTERM, signal_handler);
64
  signal(SIGINT, signal_handler);
65
  setvbuf(stdout, NULL, _IOLBF, 0);
66
  setvbuf(stderr, NULL, _IOLBF, 0);
67

    
68
  mg_mgr_init(&mgr, NULL);
69

    
70
  nc = mg_bind(&mgr, s_http_port, ev_handler);
71
  mg_set_protocol_http_websocket(nc);
72

    
73
  printf("Started on port %s\n", s_http_port);
74
  while (s_signal_received == 0) {
75
    mg_mgr_poll(&mgr, 200);
76
  }
77
  mg_mgr_free(&mgr);
78

    
79
  return 0;
80
}