views:

107

answers:

2

Server has created a socket and bound to a port and started a thread which is in loop to accept the connection. Sometime later loop exited due to an exception resulting in thread exit but socket is still bounded to port. Now if client does a 'connect' to this server, it is succeeding. How is it possible? If I understand correctly, 'connect' returns only after server does 'accept' on the listening socket. Am I missing something here?

A: 

The connected sockets go into a queue waiting for the receiving process to accept() them. There is a limited backlog of these, once it is reached the OS will start either rejecting connections or ignoring them.

MarkR
My question is when "connect" call returns? After server calls "accept" on connecting socket or when it successfully goes to listening queue? If server doesn't call "accept" , can we expect "connect" in client succeed?
kumar
You are not correct, connect will NOT wait for the server to call accept(). It only waits for a response from the OS, which generally queues the request.
MarkR
+4  A: 

If I understand correctly, 'connect' returns only after server does 'accept' on the listening socket. Am I missing something here?

Yes. TCP establishes the connection - the 3-way handshake - under the covers and puts it in a completed connection queue when it is ready. Accept() returns the next waiting connection from the front of this queue.

From the client's perspective it is "connected" but it won't be talking to anyone until the server accepts and begins processing. Sort of like when you call a company and are immediately put in the hold queue. You are "connected" but no business is going to be done until someone actually picks up and starts talking.

Your individual thread may have died but the process is still alive and the file descriptor still open so TCP doesn't know what is going on at the application level.

Duck
The difference between the phone service hold queue and a TCP connection which has been not-yet accept()ed: whatever bytes are sent down the TCP connection are buffered by the operating system, and are received once the call to accept() has been made. On the phone system hold line, whatever is said by the caller is discarded.
Heath Hunnicutt
I was debating whether to add that so thanks. Of course there is nothing to say that the phone service *isn't* recording you while you think you are on hold and it is piping out muzak. :)
Duck
It's also worth pointing out that this is what the `backlog` parameter to the `listen()` call is all about - the backlog is the number of connections that can be in that connnected-but-not-accepted state at any one time.
caf
Excellent. Now I understand this behavior better. Thanks a lot Duck and Heath.
kumar