天天看點

完全釋放socket資源,以便重連的方法。

伺服器限制了隻能有一個連接配接。關閉連接配接時,使用如下代碼都無法釋放TCP資源:

try
{
    if (this.clientSocket == null) return;
    //this.clientSocket.Shutdown(SocketShutdown.Both);
    this.clientSocket.Disconnect(false);
    //this.clientSocket.Close();
    this.clientSocket.Dispose();
}
catch (SocketException sEx)
{
    Common.DebugLogger.WLog_Error(sEx.Message);
}
finally
{
    this.clientSocket = null;
}
           

解決方案:

 重新建立socket 的上一級類的執行個體(重新開機整個程式也可以。。。)

public void DisConnect()
        {
            this.tcpNet.Disconnect();
            this.tcpNet = new TcpNet();// 重新建立socket 的上一級類的執行個體
        }
           
public class TcpNet : ITcp
{
     Socket clientSocket = null;
}
           
完全釋放socket資源,以便重連的方法。