在Socket的超时时间默认20多秒,而实际连上不需1秒时间,20多秒很多时候用户是不能接受的,而在等待返回结果的这段时间里程序会处于停止响应状态!废话不多说了,先上代码!
private delegate string ConnectSocketDelegate(IPEndPoint ipep, Socket sock);
private string ConnectSocket(IPEndPoint ipep, Socket sock)
{
string exmessage = "";
try
{
sock.Connect(ipep);
}
catch (System.Exception ex)
{
exmessage = ex.Message;
}
finally
{
}
return exmessage;
}
private void Button1_Click(object sender, EventArgs e)
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.4.1"), 8266);//IP和端口
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ConnectSocketDelegate connect = ConnectSocket;
IAsyncResult asyncResult = connect.BeginInvoke(ipep, sock, null, null);
bool connectSuccess = asyncResult.AsyncWaitHandle.WaitOne(2000, false); //2秒后结束
if (!connectSuccess)
{
MessageBox.Show(string.Format("连接失败!错误信息:{0}", "连接超时"));//2秒后弹出
}
}