Reuse TCPSocket created from ServerSocket

I have gone through this forum up and down, and I just feel like I’m missing something.

Lets talk ServerSocket and TCPSocket

I have a console application that I am using ServerSocket. It creates 12 TCPSocket, no problem.

I can telnet to my console app, and i can see it uses one of the TCPSockets that the ServerSocket.AddSocket created.

If I disconnect the telnet session, the TCPSocket error event is called with lostconnection 102 error. In there I am calling the close method on itself to hopefully re-use this TCPSocket. I get no error.

I reconnect and it will use a different socket from the pool of 12… No problem, there is a TIME_WAIT state… I get that… I check netstat to verify the connection is no longer in a TIME_WAIT state and it’s completely gone, but once I have used about 10 of the 12 pooled TCPSockets that ServerSocket created, it doesn’t re-use any of the ones that were initially created and ServerSocket generates 10 more… So now I have 22 instances of a TCPSocket.

How can I re-use these TCPSockets?

IIRC ServerSocket will never allow a new connection to a “used” socket, but the disconnected sockets should be disposed of in due course. You could try Self = Nil in the error handler for a 102 error to remove the closed sockets.

You don’t have to call Close (that’s what the error event is telling you already happened) nor do you need to set it to Nil as that happens after the Close event fires.

And no, you can’t “reuse” sockets. New ones are created from scratch whenever they need to be. To avoid any delays, make sure the MinimumAvailableSockets is set to a sufficient number. The default is 2 and if a lot of connections are being made and destroyed, it’ll get sluggish.