In network programs, a server is usually used to process multiple clients. In order to make requests from multiple clients, the server programs have different processing methods.
Currently, the most common server models are as follows:
Cyclic server: the cyclic server can only respond to requests from one client at a time.
Concurrent Server: the concurrent server can respond to requests from multiple clients at the same time.
Cycle Server Model:
TCP
Socket (...);
BIND (...);
Listen ();
While (1)
{
Accept ();
While (1)
{
Recv ();
Process ();
Send ();
}
Close ();
}
UDP
Socket ();
BIND ();
While (1)
{
Recvfrom ();
Process ();
Sendto ();
}
Concurrent Server:
To make up for the defects of the TCP cyclic server, the concurrency server model is involved.
The idea of a concurrent server is that the server accepts client connection requests and creates a sub-process to serve the client.
The TCP concurrent server can prevent the client from occupying the server exclusively in the TCP cyclic server.
The process is as follows:
Socket ();
BIND ();
Listen ();
While (1)
{
Accept (); // constant acceptance wait
If (Fork () = 0) // create a sub-process
{
While (1) {Recv (); process (); send ();}
Close (); // close the processed socket
Exit ();
}
Close (...); // close the parent process
}
If there are too many clients, you need to create multiple sub-processes, but too many sub-processes will affect the running efficiency of the server.
UDP
Same as TCP.
I/O multiplexing Concurrent Server
Initialization (socket-> bind-> listen );
While (1 ){
Sets a collection of listener read/write file descriptors (FD _*);
Call select;
If the listening socket is ready, there is a new connection request {
Establish a connection (accept );
Added to the collection of listener file descriptors;
}
Otherwise, it indicates a descriptor already connected {
Process Operation (send or Recv)
}
}
The I/O multiplexing model can solve the problem of resource restrictions. This model actually uses the UDP Loop Model
TCP.
The server uses a single process to process requests cyclically.