Example4: udpecho_server Description This example implements a simple UDP echo server. It listens on Port 7 for connection requests. After a client connects, it will echo back each message that it receives. This code was intended as a simple example of a UDP server program. In order to keep the code simple, it will handle only one connection at a time. It will only return the first 255 bytes of any requests that are longer than 255 bytes. You can connect to the example echo server with another embTCP system running the UDP echo client of Example1, or you may use any other UDP echo client. The initialization routine for all of the embTCP example programs is called example_init. For this reason, you can only link with one example at a time on an embTCP system. When example_init is called, it will create and initialize a task and begin running. Code Walkthrough In udpecho_server.c, after a few definitions and prototypes, the next section defines the UDP task info structure and calls TK_CREATE to create the UDP echo server task. The function example_init() creates udp echo server task. Task body tk_ts_echo waits until the network is ready and then calls udp_secho_init. udp_secho_init() calls the main loop of the echo server. udp_secho_init() only returns if there is an error setting up the listening socket. If it does return, the task will be deleted. The udp_secho_init() routine does the following: * Sets up a socket address structure for listening on port 7 for a connection request from any IP4 address. * Calls t_socket()and t_bind() * Uses t_setsocketopt to put the socket in non-blocking mode. This is important because the echo server uses two sockets: one for listening for connection requests and another that is created to listen for incoming messages from an accepted connection. If the listening socket were to block waiting for another connection request, the echo server would not be able to service the requests for the connected socket. * Allocates a read buffer and calls udp_echo_poll(); The udp_echo_poll() routine does the following: * Goes into a loop. The "for(;;)" expression means it will only exit when "return" is called. * Call t_recvfrom to read any messages received on es_sock. A return of 0 means the peer closed the socket. A zero return causes us to return and close the socket. * If len > 0, we call tesvrecho() to echo back the received data. The t_recvfrom call fills out the socket address structure "him" with the address of the caller. The udp_secho_close() routine simply prints a closing message and returns.