TCP/UDP client and server

What is Plain TCP / UDP?

TCP stands for Transmission Control Protocol. It is a connection-oriented protocol and originated in the initial network implementation in which it complemented the IP, hence TCP/IP. The Web, email and many file transfer systems rely on TCP. Basically anything that requires high reliability and transmission time is relatively less critical.

For applications that don’t require this level of reliability UDP is an option. It stands for User Datagram Protocol and is a connectionless protocol. It’s great for application that need a fast transmission and is useful for servers that answer small queries from a large number of clients.

Why is Plain TCP / UDP important for connectivity?

If you were to place HTTP, TCP and UDP in hierarchy of application level protocols, you would have HTTP on top, followed by TCP and then UDP. Most protocols are underlined with TCP or UDP. And, if you have either of these you can implement other protocols relatively easily. In fact, you could invent your own protocol and use plain TCP/UDP for delivering packets.

In the embedded world, are the most lightweight protocols. Both just deliver packets with raw data. For example, if you want a chip to send the temperature of a room every 10 minutes to the server, you can utilise UDP. This would be a simple implementation. And, while UDP doesn’t guarantee delivery, for a simply application like this, the risk would be worth the gain. Key is the small footprint, which is vital for any device with a low amount of memory.

Plain TCP / UDP and Mongoose Embedded Web Server

Plain TCP and Plain UDP are the base of the other protocols in Mongoose. Once mg_connect or mg_bind are called, you have a pure TCP (or UDP, depending on parameters) connection. And, while one of mg_set_protocol_xxxx is not called, it is still a TCP/UDP connection. It is extremely simple to send and receive data through these connections. Check out the examples!

TCP server example

Create listening connection:

c = mg_bind(&mgr, "1234", ev_handler);

An handle events:

void ev_handler(struct mg_connection *c, int ev, void *ev_data) {
  switch (ev) {
    case MG_EV_RECV:
      /* Echo received message back */
      mg_send(c, c->recv_mbuf.buf, c->recv_mbuf.len);
      mbuf_remove(&c->recv.mbuf, c->recv_mbuf.len);
      ...

TCP client example

Make a connection to the CoAP server:

c = mg_connect(&mgr, "my.server:1234", ev_handler);

An handle events:

void ev_handler(struct mg_connection *c, int ev, void *ev_data) {
  switch (ev) {
    case MG_EV_CONNECT:
      mg_printf(c, "%s", "hi there");
      break;
      ...

All examples

SEE ALL EXAMPLES DOWNLOAD SOURCE CODE