在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秒後彈出
}
}