When reading through this Async Sockets example, I find this code:
// Get the socket that handles the client request.
Socket listener = (Socket) ar.AsyncState;
Socket handler = listener.EndAccept(ar);
I’m having trouble finding documentation on what the difference between these 2 sockets is and I’d also like to know how shutting down the handler, or closing the handler will effect the original socket. Can anyone explain this, or point me to some documentation?
A socket is a unique connection on a particular machine i.e.
127.0.0.1:1024. Only one active connection can be made at a time. The “listener” listens on a fix port (e.g. 1024 in my above example). It’s job is to be a “public” way of accepting connections. Once it accepts a connection it creates a new socket on a new, randomly (well, reasonably pseudo-randomly), select port. Then the original connecting application and the host can communicate over that socket freeing the listening socket to get another connection (which would dole out another port number for a new connection, and so on).EndAcceptis usually all you need to do once you’ve got a connection. Thelistenerusually goes on the listen for more connections to accept. If not, you’ll usually just dispose or close the socket to stop listening and cancel any pending accepts. Thehandleris used to do whatever communication your application needs to, completely independently of thelistenersocket. When you’re done with thehandlersocket you dispose or close it and because thelisteneris independent it continues “running”.Shutdownwill flush any pending data on a connection-oriented socket (to be called beforeClose) and won’t affect any other sockets.