I am working with some legacy TCP server code that works with sockets directly as it was written in .NET 2.0 and earlier. The server has a feature to 'stop' and 'start' accepting client connections.
To troubleshoot the issue I run the server in the console mode as admin user. On top of that I have eliminated the socket accept thread from the equation and all the code does is something like:
tcpListener = new TcpListener(IPAddress.Any, this.Port);
This called from different methods. I have debugged the code and I am pretty sure the code executes only once. However, the issue is that call to
Stop does not actually releases the socket address and subsequent call to
Start therefore fails with the error "Only one usage of each socket address (protocol/network address/port) is normally permitted". I can also confirm from the ProcessExplorer that the server is still listening on the server port.
When I write a small console app that uses the same code snippets everything works fine. I have even tried tracing the .NET network and socket libraries, but there is no error or anything to indicate problems there.
It is not clear to me why call to
Stop does not release the socket address?
After more investigation it turns out that there is some strange effect of child process launch to the
TcpListener. I have made a 'bare bone' sample code that illustrates the issue:
public static void Main(string args)
Int32 port = 13000;
if (args.Length > 0) // indicates child process