Monday, August 22, 2011

Understanding the Role of accept(2) function in socket

It might seem strange for accept(2) to return yet another socket. After all, wouldn't it be better to use the original socket? The answer lies in the nature of most server designs. A server, upon
accepting one client connection, must be willing to accept additional connections from clients. Any individual socket, however, can only be connected to one client. Where would the www.woohoo.com server be if it could only service one client at one time?
Figure, which was presented earlier, was an oversimplification of server responsibilities. Figure below is an improvement, showing the steps that a simple server would use.


Figure :
Here is an improved diagram explaining the connection steps for client and server (note the repetition of steps S4 to S6).
Figure above shows how the server will repeat steps S4 through S6 for each client that connects. The server finishes processing each client's request with a close(2) function call in step S6. However,
to continue to receive new connections, the server needs its original socket that is able to listen for additional requests.
To summarize, there are two types of sockets used by the server program. They are
  • Sockets that are being used for listening (passed to the listen(2) function call at one point). No reading or writing of data to these sockets is permitted.
  • Sockets that have been returned by accept(2). These are connected to a client process, and can be used to read and write data.

The socket is made into a "listening socket" by passing it to the listen(2) function. A socket returned from accept(2) is a connected socket, which can be read from or written to.

NOTE
The input socket to the accept(2) call must be a listening socket. Any attempt to use a non-listening socket will cause the function to return an error.

You must be sure to understand these concepts in order to write a TCP/IP server program. If this is still unclear to you, the example program presented here will help to clarify all of this. This time I am also giving the step by step explanation of the source code also.

No comments:

Post a Comment