最近在做一个端口高速扫描器,在参考http://blog.csdn.net/hany3000/article/details/42422667 的博文时,发现一些问题,可能对读者造成误解,下面将对这个问题重新讲解
class Scanner
{
private ManualResetEvent TimeoutObject = new ManualResetEvent(false);//设置为false,使下次调用waitone阻塞线程,若为true,waitone将不会阻塞线程
string m_host;
int m_port;
public Scanner(string host, int port)
{
m_host = host;
m_port = port;
}
public void Scan()
{
//TimeoutObject.Reset();//此处没有必要
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
try
{
socket.BeginConnect(m_host, m_port, o => { TimeoutObject.Set(); //更改ManualResetEvent标志位为true,并通知waitone检测标志位 }, null);
TimeoutObject.WaitOne(200, false);//此处阻塞线程,超时200MS
if (socket.Connected)
{
Program.IpList.Add(m_host);
Console.WriteLine(m_host + " 已连接");
}
else
{
Console.WriteLine(m_host + " 无法连接");
}
socket.Dispose();
}
catch (Exception)
{
socket.Dispose();
}
}
}