2012-03-28 140 views
2

我在C#中使用Windows窗體應用程序。我正在使用以異步方式連接到服務器的套接字客戶端。 我想套接字嘗試立即重新連接到服務器,如果連接因任何原因中斷。 我接受常規看起來像這樣自動重新連接異步套接字客戶端

 public void StartReceiving() 
    { 
     StateObject state = new StateObject(); 
     state.workSocket = this.socketClient; 
     socketClient.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(OnDataReceived), state); 
    } 

    private void OnDataReceived(IAsyncResult ar) 
    { 
     try 
     { 
      StateObject state = (StateObject)ar.AsyncState; 
      Socket client = state.workSocket; 

      // Read data from the remote device. 
      int iReadBytes = client.EndReceive(ar); 
      if (iReadBytes > 0) 
      { 
       byte[] bytesReceived = new byte[iReadBytes]; 
       Buffer.BlockCopy(state.buffer, 0, bytesReceived, 0, iReadBytes); 
       this.responseList.Enqueue(bytesReceived); 
       StartReceiving(); 
       receiveDone.Set(); 
      } 
      else 
      { 
       NotifyClientStatusSubscribers(false); 
      } 
     } 
     catch (Exception e) 
     { 

     } 
    } 

當NotifyClientStatusSubscribers(假)被稱爲執行功能StopClient:

public void StopClient() 
    { 
     this.canRun = false; 
     this.socketClient.Shutdown(SocketShutdown.Both); 
     socketClient.BeginDisconnect(true, new AsyncCallback(DisconnectCallback), this.socketClient); 
    } 

    private void DisconnectCallback(IAsyncResult ar) 
    { 
     try 
     { 
      // Retrieve the socket from the state object. 
      Socket client = (Socket)ar.AsyncState; 

      // Complete the disconnection. 
      client.EndDisconnect(ar); 

      this.socketClient.Close(); 
      this.socketClient = null; 
     } 
     catch (Exception e) 
     { 

     } 
    } 

現在,我嘗試通過調用以下功能重新連接:

public void StartClient() 
    { 
     this.canRun = true; 
     this.MessageProcessingThread = new Thread(this.MessageProcessingThreadStart); 
     this.MessageProcessingThread.Start(); 
     this.socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
     this.socketClient.LingerState.Enabled = false; 
    } 

    public void StartConnecting() 
    { 
     socketClient.BeginConnect(this.remoteEP, new AsyncCallback(ConnectCallback), this.socketClient); 
    } 

    private void ConnectCallback(IAsyncResult ar) 
    { 
     try 
     { 
      // Retrieve the socket from the state object. 
      Socket client = (Socket)ar.AsyncState; 

      // Complete the connection. 
      client.EndConnect(ar); 

      // Signal that the connection has been made. 
      connectDone.Set(); 

      StartReceiving(); 

      NotifyClientStatusSubscribers(true); 
     } 
     catch(Exception e) 
     { 
      StartConnecting(); 
     } 
    } 

當連接可用時套接字重新連接,但在幾秒鐘後,我得到以下未處理的異常:「」連接請求是在已連接的套接字上進行的。「

這怎麼可能?

回答

2

如果您在ConnectCallback中遇到異常並且實際上已成功連接,則可能有此情況。在ConnectCallback的catch語句中設置一個斷點,並查看是否有異常提升到那裏 - 目前沒有任何東西會告訴您存在異常。