Mishax
Mishax

Reputation: 4582

How to unbind a socket server in IIS

I have an IIS 6.1 application in which I am attempting to maintain a socket server but I can't free the port:

In Global.asax.cs Application_Start I start a thread ProgramConnectionServerThread in which I've got:

int programPort = ServerConfiguration.Instance.ProgramConnectionPort;
ServerConfiguration.Instance.ProgramConnectionSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket listener = ServerConfiguration.Instance.ProgramConnectionSocket;
IPEndPoint localEndPoint = new IPEndPoint(Dns.Resolve(Dns.GetHostName()).AddressList[0], programPort);

listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
    Socket handler = listener.Accept();
    // action
}

and in Global.asax.cs Dispose

try
{
    if (ServerConfiguration.Instance.ProgramConnectionServerThread != null)
    {
        ServerConfiguration.Instance.ProgramConnectionServerThread.Abort();
    }
}
catch (Exception eeg2)
{
// Log
}
try
{
    LingerOption lo = new LingerOption(false, 0);
    ServerConfiguration.Instance.ProgramConnectionSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lo);
    ServerConfiguration.Instance.ProgramConnectionSocket.Shutdown(SocketShutdown.Both);
    ServerConfiguration.Instance.ProgramConnectionSocket.Close(); // this is Line 133
}
catch (Exception eeg2)
{
// Log
}

This approach does not seem to be working. In my logging I get the following error message on the Close() invocation:

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)
   at Contoso.Global.Dispose() in E:\Contoso\Global.asax.cs:line 133

If I restart the web site in IIS the port is not free! I get this message when I do the bind:

System.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted

How do I free this port so on subsequent restarts of the application I can bind a new listener?

Upvotes: 2

Views: 658

Answers (1)

usr
usr

Reputation: 171178

I have seen the line numbers to be off by one sometimes. The stack trace clearly tells you it came from Shutdown.

A listening socket is never connected. Why are you shutting it down? Make sure you understand what Shutdown does.

Do not abort threads.

Using an ASP.NET app as a socket server is hard to get right. Worker process lifetimes can overlap, as you probably have observed. That would be a new question however.

Upvotes: 2

Related Questions