考虑以下程序:
using System;
using System.Diagnostics;
using System.Net.Sockets;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Socket sock = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
try
{
Stopwatch watch = new Stopwatch();
watch.Start();
IAsyncResult res = sock.BeginConnect("localhost", 7000, null, null);
res.AsyncWaitHandle.WaitOne( 5000 ); // 5 sec timeout
watch.Stop();
Console.WriteLine("Elapsed ms: " + watch.ElapsedMilliseconds);
if (!sock.Connected) {
sock.Close();
Console.WriteLine("Failed to connect server.");
}
}
catch (System.Exception ex) {
Console.WriteLine(ex.Message);
}
}
}
}
控制台输出:
Elapsed ms: 1014
Failed to connect server.
我本来希望BeginConnect
尝试建立连接大约 5 秒,而等待总是在 1 秒后返回。为什么?