c#socket异步连接后怎样判断连接是否成功
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();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询