UDP Servers

TCP servers are complex, especially when several clients are to be handled. UDP, on the other hand, provides a much easier communications mechanism. The downside is reduced reliability and security, but for fast-action games, UDP is the way to go. As you already know, UDP does not maintain a fixed connection, so each packet must come identified with its source. We read packets with recvfrom and send them back with sendto. Using the same sockaddr structure for both calls guarantees perfect echoing, thus, returning the packet to its originator. Here is a simple echo example:

 void do_echo(int sockfd) { struct sockaddr *pcli_addr; char mesg[MAXMESG]; while (1)    {    int n = recvfrom(sockfd, mesg, MAXMESG, 0, pcli_addr, &clilen);    nosent = sendto(sockfd, mesg, n, 0, pcli_addr, clilen);    } } 

The socket has already been opened and bound to an address. Then, we loop, reading packages and sending them back to the client. This is a connectionless, stateless server. It does not store any state information, but just acts like a data relay.

Core Techniques and Algorithms in Game Programming2003
Core Techniques and Algorithms in Game Programming2003
Year: 2004
Pages: 261

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net