listen()
and accept()
are two completely different operations. Yourr understanding of how they work is incorrect.
listen()
merely sets up the listening socket's backlog and opens the bound port, so clients can start connecting to the socket. That opening is a very quick operation, there is no need to worry about it blocking.
A 3-way handshake is not performed by listen()
. It is performed by the kernel when a client tries to connect to the opened port and gets placed into the listening socket's backlog. Each new client connection performs its own 3-way handshake.
Once a client connection is fully handshaked, that connection is made available for accept()
to extract it from the backlog. accept()
blocks (or, if you use a non-blocking listening socket, accept()
succeeds) only when a new client connection is available for subsequent communication.
You call listen()
only 1 time, to open the listening port, that is all it does. Then you have to call accept()
for each client that you want to communicate with. That is why accept()
blocks and listen()
does not.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…