突然,由于套接字异常,服务器无法连接

本文关键字:连接 服务器 套接字 突然 异常 | 更新日期: 2023-09-27 18:31:18

我正在使用MSND中的这个服务器示例:http://msdn.microsoft.com/en-us/library/fx6588te.aspx

由于某种原因,我的服务器拒绝在_listener.Bind(localEndPoint);连接此功能,并出现错误Only one usage of each socket address (protocol/network address/port) is normally permitted

直到几分钟前,我没有任何问题Sarver连接没有问题,突然发生了

public static void StartListening(IPAddress ipAddress, int port)
{
    _isServerRunning = true;
    // Data buffer for incoming data.
    byte[] bytes = new Byte[1024];
    // Establish the local endpoint for the socket.
    // The DNS name of the computer
    // running the listener is "host.contoso.com".
    //IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
    //IPAddress ipAddress = IPAddress.Parse("192.168.0.100"); //ipHostInfo.AddressList[0];
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
    // Create a TCP/IP socket.
    _listener = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream, ProtocolType.Tcp);
    // Bind the socket to the local endpoint and listen for incoming connections.
    try
    {
        _listener.Bind(localEndPoint);
        _listener.Listen(100);
        while (true)
        {
            // Set the event to nonsignaled state.
            allDone.Reset();
            // Start an asynchronous socket to listen for connections.
            Console.WriteLine("Waiting for a connection...");
            _listener.BeginAccept(
                new AsyncCallback(AcceptCallback),
                _listener);
            // Wait until a connection is made before continuing.
            allDone.WaitOne();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
    //Console.WriteLine("'nPress ENTER to continue...");
    Console.Read();
}

此错误是什么意思?

突然,由于套接字异常,服务器无法连接

这很可能意味着本地端口仍处于保留状态。 这可能是因为另一个进程仍在运行并保持 sockewt 打开状态,或者因为dSO_LINGER套接字选项定义的超时期限未超时。 我不熟悉 c#,但应该有一种方法可以设置 elinger 超时。

您可以使用 netstat 命令判断套接字的当前状态。

我想你可以在这里找到一些解决方案 http://blogs.msdn.com/b/dgorti/archive/2005/09/18/470766.aspx