2012-03-28 137 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语句中设置一个断点,并查看是否有异常提升到那里 - 目前没有任何东西会告诉您存在异常。