c#socket异步连接后怎样判断连接是否成功

2024-11-25 05:41:18
推荐回答(1个)
回答1:

//这是例子,你参考参考
private  int connToServer(string hostip, int hostport,int ctimeout)       
 {            
IPEndPoint remoteEp = new IPEndPoint(IPAddress.Parse(hostip),hostport);            try            
{                
connDone.Reset();
                //开始连接                
cliSock.BeginConnect(remoteEp, new AsyncCallback(connCallBack), cliSock);                connDone.WaitOne(ctimeout, false);              
  if (!cliSock.Connected)                
{                    //连接超时                    
return CONNTIMEOUT;                }                
//连接成功               
 return 0;            }            
catch (SocketException ex)            
{                //连接失败                
cliSock.Close();                
return CONNTIMEOUT;           
 }           
 catch (Exception ex)       
     {                //连接失败            
    cliSock.Close();             
   return CONNTIMEOUT;         
   }      
  }       
 private  void connCallBack(IAsyncResult ar)       
 {            
Socket s = (Socket)ar.AsyncState;         
   try           
 {               
 s.EndConnect(ar);               
 isConnected = s.Connected;      
      }           
 catch (Exception ex)     
       {               
 isConnected = false;      
          //发生错误            
    return;          
  }           
 finally        
    {             
   connDone.Set();    
        }      
  }