question

DarrylHoar-5879 avatar image
0 Votes"
DarrylHoar-5879 asked DanielZhang-MSFT answered

how to free a socket still bound to a previous crash c#

Visual Studio 2019 c#.
I created a custom service. It listens to a specific port to communicate with another piece of software on the computer using the TcpListener.
tcpListener serverSocket = new TcpListener(localAddr, port)

try {
serverSocket.Start();
//process stuff in here
}

If the service hangs and has to be force restarted or crashes, the socket does not get "released" and when the service tries to start again, I get an error that the socket in already in use.

Is there anyway to handle this situation ? The only way I have found to "clear" it is to reboot the computer.

Any ideas greatly appreciated.

dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

DanielZhang-MSFT avatar image
0 Votes"
DanielZhang-MSFT answered

Hi DarrylHoar-5879,
You need to stop listening for new clients in finally statement.
Code looks like below:

 try 
 {
 serverSocket.Start();
 //process stuff in here
 }
 catch(SocketException e)
 {
       Console.WriteLine("SocketException: {0}", e);
 }
 finally
 {
        // Stop listening for new clients.
        serverSocket.Stop();
 }

Best Regards,
Daniel Zhang


If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.