|
In recent years, RFID readers, smart home gateways, temperature and humidity sensors are often used in work, generally there are serial ports and network ports, due to on-site reasons, serial ports are generally less used, most of them use network ports. The connection method is IP address and port, some devices have search software, some do not. Frequent use of the test environment and the site is inevitably confusing. A recent RFID reader uses a ZN-100 Ethernet port-to-serial port module, and the search software (ZNetCom Utility) is good and the search speed is also very fast. (As shown below)
I thought about developing one myself, first of all, the IP segment and port can be customized, which is easy to use; The search speed must be fast, and I am in a hurry to use multithreading and asynchronous. Let's take a picture first.
- #region 扫描方法
- public void Scan(string m_host, int m_port)
- {
- //我们直接使用比较高级的TcpClient类
- TcpClient tc = new TcpClient();
- //设置超时时间
- tc.SendTimeout = tc.ReceiveTimeout = 2000;
- try
- {
- //同步方法
- //IPAddress ip = IPAddress.Parse(host);
- //IPEndPoint IPendp = new IPEndPoint(ip, port);
- //tc.Connect(IPendp);
- //异步方法
- IAsyncResult oAsyncResult = tc.BeginConnect(m_host, m_port, null, null);
- oAsyncResult.AsyncWaitHandle.WaitOne(1000, true);//1000为超时时间
- if (tc.Connected)
- {
- //如果连接上,证明此端口为开放状态
- UpdateListBox(listBox1, m_host + ":" + m_port.ToString());
- }
- }
- catch (System.Net.Sockets.SocketException e)
- {
- //容错处理
- //MessageBox.Show("Port {0} is closed", host.ToString());
- //Console.WriteLine(e.Message);
- }
- finally
- {
- tc.Close();
- tc = null;
- scannedCount++;
- runningThreadCount--;
- }
- }
- #endregion
- 如果使用同步方法会有明显的卡顿,用户体验不好;使用异步感觉很流畅,很爽,自己可以注释代码亲测。
Copy codeSource code contributes:
IP端口扫描.rar
(31.73 KB, Number of downloads: 12)
|