Statistics
| Branch: | Tag: | Revision:

mongoose / examples / udp_echo_server / echo_server.c @ eaef5bd1

History | View | Annotate | Download (1.79 KB)

1
// Copyright (c) 2016 Cesanta Software Limited
2
// All rights reserved
3
//
4
// This software is dual-licensed: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License version 2 as
6
// published by the Free Software Foundation. For the terms of this
7
// license, see <http://www.gnu.org/licenses/>.
8
//
9
// You are free to use this software under the terms of the GNU General
10
// Public License, but WITHOUT ANY WARRANTY; without even the implied
11
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
// See the GNU General Public License for more details.
13
//
14
// Alternatively, you can license this software under a commercial
15
// license, as set out in <https://www.cesanta.com/license>.
16
//
17

    
18
#include "mongoose.h"
19

    
20
static void ev_handler(struct mg_connection *nc, int ev, void *p) {
21
  struct mbuf *io = &nc->recv_mbuf;
22
  (void) p;
23
  switch (ev) {
24
    case MG_EV_RECV:
25
      mg_send(nc, io->buf, io->len);  // Echo message back
26
      mbuf_remove(io, io->len);       // Discard message from recv buffer
27
      // In case of UDP, Mongoose creates new virtual connection for
28
      // incoming messages
29
      // We can keep it (and it will be reused for another messages from
30
      // the same address) or we can close it (this saves some memory, but
31
      // decreases perfomance, because it forces creation of connection
32
      // for every incoming dgram)
33
      nc->flags |= MG_F_SEND_AND_CLOSE;
34
      break;
35
    default:
36
      break;
37
  }
38
}
39

    
40
int main(void) {
41
  struct mg_mgr mgr;
42
  const char *port1 = "udp://1234", *port2 = "udp://127.0.0.1:17000";
43

    
44
  mg_mgr_init(&mgr, NULL);
45
  mg_bind(&mgr, port1, ev_handler);
46
  mg_bind(&mgr, port2, ev_handler);
47

    
48
  printf("Starting echo mgr on ports %s, %s\n", port1, port2);
49
  for (;;) {
50
    mg_mgr_poll(&mgr, 1000);
51
  }
52
  mg_mgr_free(&mgr);
53

    
54
  return 0;
55
}