2015-12-16 73 views
0

我有以下兩個函數來啓動和停止「本地服務器」(套接字監聽器)。套接字重用不起作用

public String startServer(Int32 port, Int32 maximumPendingConnections, ref String errorMsg) { 
    try { 
     // Creates one SocketPermission object for access restrictions 
     permission = new SocketPermission(
     NetworkAccess.Accept,  // Allowed to accept connections 
     TransportType.Tcp,  // Defines transport types 
     "",      // The IP addresses of local host 
     SocketPermission.AllPorts // Specifies all ports 
     ); 
     // Listening Socket object 
     sListener = null; 
     // Ensures the code to have permission to access a Socket 
     permission.Demand(); 
     // Resolves a host name to an IPHostEntry instance 
     IPHostEntry ipHost = Dns.GetHostEntry(""); 
     // Gets first IP address associated with a localhost 
     ipAddr = ipHost.AddressList[0]; 
     // Creates a network endpoint 
     ipEndPoint = new IPEndPoint(ipAddr, port); 
     // Create one Socket object to listen the incoming connection 
     sListener = new Socket(
      ipAddr.AddressFamily, 
      SocketType.Stream, 
      ProtocolType.Tcp 
      ); 
     // Associates a Socket with a local endpoint 
     sListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //newly added as an answer 
     sListener.Bind(ipEndPoint); 
     sListener.Listen(maximumPendingConnections); 

     // Begins an asynchronous operation to accept an attempt 
     AsyncCallback aCallback = new AsyncCallback(AcceptCallback); 
     sListener.BeginAccept(aCallback, sListener); 
    } catch (Exception e) { 
     //ErrorHandling 
    } 
    return ipAddr.ToString(); 
} 

停止連接:

public void stopServer(ref String errorMsg) { 
    try { 
     sListener.Shutdown(SocketShutdown.Both); 
     sListener.Disconnect(true); 
     sListener.Close(); 
     sListener.Dispose(); 
    } catch (Exception e) { 
     //Errorhandling 
    } 
} 

我已經讓你無法重複使用套接字發現,但是如果你設置sListener.Disconnect(true);它應該能夠重新使用。除此之外,我每次開始創建一個新的套接字。我在這裏錯過了什麼?

它給出了每個套接字只能使用一次的錯誤。它提供了14:41的sListener.Bind(ipEndPoint);

@Edit錯誤 - 16-12-2015 我發現,如果我的sListener.Bind(ipEndPoint);它的工作原理之前添加以下代碼行;

sListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); 

回答

1

如果你想真正重用插座,不要做ShutdownCloseDispose,因爲這些調用返回的套接字操作系統使用的資源。基本上,你的套接字處理程序變得無效,然後Disconnect(true)完成的工作是徒勞的。

(你也不需要做ShutdownClose在同一時間,只要Close會做的伎倆。)

1

Connected屬性將始終返回false因爲套接字處於偵聽狀態,沒有連接。不幸的是,不能「解除」套接字,所以你必須關閉它並創建新套接字。

另一個問題是:序列Shutdown,Disconnect,CloseDispose看起來像踢死屍體。

+0

謝謝您關於連接財產的額外建議。我會改變這個,序列就是vovanrock所說的。但我想我只是喜歡踢:-p(也會改變這個問題) – Sliver2009