2016-05-12 04:36:12 +08:00
|
|
|
---
|
2016-09-01 22:19:01 +08:00
|
|
|
title: Example - TCP echo server
|
2016-05-12 04:36:12 +08:00
|
|
|
---
|
2016-03-17 20:06:04 +08:00
|
|
|
|
2016-05-12 04:36:12 +08:00
|
|
|
- Copy `mongoose.c` and `mongoose.h` to your build tree
|
2016-07-21 21:30:03 +08:00
|
|
|
- Write code that uses the Mongoose API, e.g. in `my_app.c`
|
2016-05-12 04:36:12 +08:00
|
|
|
- Compile application: `$ cc my_app.c mongoose.c`
|
2016-03-17 20:06:04 +08:00
|
|
|
|
2016-05-12 04:36:12 +08:00
|
|
|
```c
|
|
|
|
#include "mongoose.h" // Include Mongoose API definitions
|
2016-03-17 20:06:04 +08:00
|
|
|
|
2016-05-12 04:36:12 +08:00
|
|
|
// Define an event handler function
|
|
|
|
static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
|
2016-03-17 20:06:04 +08:00
|
|
|
struct mbuf *io = &nc->recv_mbuf;
|
|
|
|
|
|
|
|
switch (ev) {
|
|
|
|
case MG_EV_RECV:
|
|
|
|
// This event handler implements simple TCP echo server
|
|
|
|
mg_send(nc, io->buf, io->len); // Echo received data back
|
|
|
|
mbuf_remove(io, io->len); // Discard data from recv buffer
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
int main(void) {
|
|
|
|
struct mg_mgr mgr;
|
|
|
|
|
2016-05-12 04:36:12 +08:00
|
|
|
mg_mgr_init(&mgr, NULL); // Initialize event manager object
|
2016-03-17 20:06:04 +08:00
|
|
|
|
|
|
|
// Note that many connections can be added to a single event manager
|
|
|
|
// Connections can be created at any point, e.g. in event handler function
|
2016-05-12 04:36:12 +08:00
|
|
|
mg_bind(&mgr, "1234", ev_handler); // Create listening connection and add it to the event manager
|
2016-03-17 20:06:04 +08:00
|
|
|
|
2016-05-12 04:36:12 +08:00
|
|
|
for (;;) { // Start infinite event loop
|
2016-03-17 20:06:04 +08:00
|
|
|
mg_mgr_poll(&mgr, 1000);
|
|
|
|
}
|
|
|
|
|
|
|
|
mg_mgr_free(&mgr);
|
|
|
|
return 0;
|
|
|
|
}
|
2016-05-12 04:36:12 +08:00
|
|
|
```
|
2016-03-17 20:06:04 +08:00
|
|
|
|