lnical
lnical

Reputation: 163

TcpListener Socket still active after program exits

I'm trying to stop a TCP Listener as my program is exiting. I do not care about any data that is currently active on the socket or any of the active client sockets.

The socket clean up code is essentially:

try
{
    myServer.Server.Shutdown(SocketShutdown.Both)
}
catch (Exception ex)
{
     LogException(ex)
}
myServer.Server.Close(0)
myServer.Stop()

myServer is a TCPListener

On some occasions, Shutdown will thrown an exception

System.Net.Sockets.SocketException: A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied at System.Net.Sockets.Socket.Shutdown(SocketShutdown how)

Edit 2010-May-14

Upon further investigation, the exception can be thrown and the socket can be closed correctly.

Sometimes, even after the application exits netstat shows the socket is still in the LISTENING state.

I have not been able to create definitive reproduction scenario, it happens at seemingly random times.

Client Sockets are cleaned up independently.

Do you have any suggestions to help me make this socket die?

Upvotes: 12

Views: 9545

Answers (4)

OSH
OSH

Reputation: 2937

had a similar problem: - TcpListener waiting for clients to connect - Dispose on close

had the same problem (win7, win2k).

A solution that works (? so far) for me was to close each of the connections to the client when disposing of the listener. It seems that if the program exists while there are still active connections VS a client, those connection may remain after the program shuts down.

Upvotes: 0

Sorax
Sorax

Reputation: 2203

Use a finally block to call Close() in the event of an exception:

try
{
    myServer.Server.Shutdown(SocketShutdown.Both);
}
catch (Exception ex)
{
    LogException(ex);
}
finally
{
    myServer.Server.Close(0);
    myServer.Stop();
}

I'm also curious if manipulation of the underlying socket is required because of some specification you haven't mentioned? TCPListener/Client are designed you keep you from worrying about those communication mechanics in most cases.

Also, if this doesn't help, what ErrorCode is being returned by the SocketException?

Upvotes: 3

Stephen Cleary
Stephen Cleary

Reputation: 457217

After your app exits, the socket cannot be in a listening state. It may be in a wait state, however; this is perfectly normal.

Upvotes: 0

paquetp
paquetp

Reputation: 1651

Try calling Stop before Close...

Upvotes: 1

Related Questions