This function provides an iterative server, rather than providing a concurrent server as a TCP server. There is no call to fork, so a single server process has to deal with all customers. In general, most TCP servers are concurrent, and most UDP servers are iterations.
For this socket, a queued occurrence is implied in the UDP layer. In fact, each UDP socket has a receive buffer, and each datagram that arrives at the socket enters the socket receive buffer. When the process calls Recvfrom, the next datagram in the buffer is returned to the process in FIFO (first in first out) order.
Server program:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <sys /types.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #define SER V_port 3333 #define Maxline 1024 #define ERR_EXIT (m) \ Do {\ perror (m); \ EXIT (Exit_failur E);
\} while (0) typedef struct SOCKADDR SA;
void Dg_echo (int sockfd, SA *pcliaddr, socklen_t clilen) {int n;
Socklen_t Len;
Char Mesg[maxline]; for (;;)
{len = Clilen;
n = recvfrom (SOCKFD, MESG, Maxline, 0, pcliaddr, &len);
SendTo (SOCKFD, MESG, N, 0, pcliaddr, Len);
int main (int argc, char **argv) {int sockfd;
struct sockaddr_in servaddr, cliaddr;
SOCKFD = socket (af_inet, SOCK_DGRAM, 0);
Bzero (&servaddr, sizeof (SERVADDR)); servaddr.sin_family = af_inet;
SERVADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);
Servaddr.sin_port = htons (Serv_port);
Bind (SOCKFD, (SA *) &servaddr, sizeof (SERVADDR));
Dg_echo (SOCKFD, (SA *) &cliaddr, sizeof (CLIADDR)); }
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/unix/