Linux network programming | server model

Server model

In network communication, the server usually needs to handle multiple clients. Since multiple client requests may come at the same time, the server can use different methods to handle them. Generally, the server side can be implemented in two models: cyclic server model and concurrent server model

  • Cyclic server model: The server processes each client in turn until all requests of the current client are processed, and then processes the next client. The advantage of this type of model is simplicity, but the disadvantage is that it is easy to cause other clients to wait too long
  • Concurrent server model: The server adopts a multi-task mechanism (multi-process or multi-thread) to create a task for each client to process, which greatly improves the concurrent processing capability of the server

1. TCP cyclic server model

The workflow of the TCP cyclic server model is as follows

socket(...);
bind(...);
listen(...);
while(1){
    
    
   accept(...);
   process(...);
   close(...);
}

The server uses loop nesting to achieve. The outer loop extracts the connection request of each client in turn, and establishes a TCP connection. The inner loop receives and processes all data of the current client until the client closes the connection; if the current client does not finish processing, other clients must wait forever

2. TCP concurrent server model

The workflow of the TCP concurrent server model is as follows

/*****TCP多进程并发服务器模型*****/
socket(...);
bind(...);
listen(...);
while(1){
    
    
   accpet(...);
   if(fork(...) == 0)
   {
    
    
   	 process(...);
     close(...);
     exit(...);
   }
   close(...);
}
/*****TCP多线程并发服务器模型*****/
socket(...);
bind(...);
listen(...);
while(1){
    
    
   accpet(...);
   if((pthread_create(...))!==-1)
   {
    
    
     process(...);
     close(...);
     exit(...);
   }
   close(...);
}

Once the server-side parent process receives the client's connection request, it establishes a connection and creates a new child process. It means that each client has a dedicated child process on the server side to serve it; multiple child processes on the server side run at the same time (macroscopically), processing multiple clients; the parent process on the server side does not specifically handle each client's data request

3. UDP loop server model

The workflow of the UDP loop server model is as follows

socket(...);
bind(...);
while(1)
{
    
    
   recvfrom(...);
   process(...);
   sendto(...);
}

Guess you like

Origin blog.csdn.net/Chuangke_Andy/article/details/108428059