由于SocketException,突然服务器无法连接

时间:2013-09-15 12:34:33

标签: c# client-server

我在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();

}

这个错误意味着什么?

2 个答案:

答案 0 :(得分:0)

这很可能意味着本地端口仍然保留。这可能是空闲的,因为另一个进程仍在运行并保持sockewt打开,或者因为dSO_LINGER套接字选项定义的超时时间没有超时。我不熟悉c#,但应该有办法设置elinger超时。

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

答案 1 :(得分:0)

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