如何解除IIS中的套接字服务器绑定

时间:2014-09-17 15:13:00

标签: asp.net .net sockets iis

我有一个IIS 6.1应用程序,其中我试图维护套接字服务器,但我无法释放该端口:

在Global.asax.cs Application_Start中,我启动了一个我已经拥有的线程ProgramConnectionServerThread

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
}

并在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
}

这种方法似乎不起作用。在我的日志记录中,我在Close()调用上收到以下错误消息:

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

如果我在IIS中重新启动网站,则端口不是免费的!当我执行绑定时,我收到此消息:

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

如何释放此端口以便随后重新启动应用程序我可以绑定一个新的侦听器?

1 个答案:

答案 0 :(得分:2)

我有时会看到一行中的行号。堆栈跟踪清楚地告诉您它来自Shutdown

永远不会连接侦听套接字。你为什么把它关掉?确保你了解Shutdown的作用。

Do not abort threads.

使用ASP.NET应用程序作为套接字服务器很难做到。正如您可能已经观察到的那样,工作程然而,那将是一个新问题。