C#:汉王人脸通SDK示例代码(二)接收心跳包

注意:代码仅供参考,需要根据具体的设备做调整
同系列文章:

演示程序源代码下载:

FaceIdDemo-CS-20161118.zip
注意:请将FaceId.dll加入工程引用

演示程序界面:
UdpServerDemo-CS

/* ----------------------------------------------------------
 * 文件名称:Form1.cs
 * 作者:秦建辉
 * 
 * QQ:36748897
 * 
 * 博客:http://www.firstsolver.com/wordpress/
 * 
 * 开发环境:
 *      Visual Studio V2013
 *      .NET Framework 4.0
 *      
 * 版本历史: 
 *      V1.0	2014年09月12日
 *              人脸通SDK演示:接收心跳包
------------------------------------------------------------ */
using System;
using System.Collections.Generic;
using System.Management;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace Splash
{
    public partial class Form1 : Form, IDgramPacketHandler
    {
        /// <summary>
        /// 设备通信字符集编码为简体中文
        /// </summary>           
        private const Int32 DeviceCodePage = 936;

        /// <summary>
        /// 心跳包接收服务器
        /// </summary>
        private UdpClientPlus UdpServer = null;

        /// <summary>
        /// 服务器是否已运行
        /// </summary>
        private Boolean IsServerRunning = false;

        public Form1()
        {
            InitializeComponent();
        }

        private void buttonSetServerHost_Click(object sender, EventArgs e)
        {
            try
            {
                using (FaceId Client = new FaceId(textBoxDeviceIP.Text, Convert.ToInt32(textBoxDevicePort.Text)))
                {
                    String Command = "SetServerHost(ip=\"" + comboBoxServerIP.Text + "\" port=\"" + textBoxServerPort.Text + "\")";
                    String Answer;
                    if (Client.Execute(Command, out Answer, DeviceCodePage) == FaceId_ErrorCode.Success)
                    {
                        MessageBox.Show("设置服务器参数成功!", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("设置服务器参数失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void buttonClear_Click(object sender, EventArgs e)
        {
            textBoxRecords.Clear();
        }

        private void buttonStartListener_Click(object sender, EventArgs e)
        {
            if (IsServerRunning)
            {                
                UdpServer.Close();
                UdpServer = null;

                IsServerRunning = false;
                buttonStartListener.Text = "开启侦听";
            }
            else
            {
                try
                {
                    UdpServer = new UdpClientPlus(Convert.ToInt32(textBoxServerPort.Text));

                    // 设置通信密码
                    UdpServer.SecretKey = String.Empty;     // 注意:密码要和设备通信密码一致

                    UdpServer.CodePage = DeviceCodePage;    // 通信字符集为简体中文
                    UdpServer.DgramPacketHandler = this;    // 设置心跳包处理程序
                    UdpServer.StartListenThread(new String[] { textBoxDeviceIP.Text });
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                IsServerRunning = true;
                buttonStartListener.Text = "停止侦听";
            }
        }

        // 实现 IDgramPacketHandler 接口,心跳包数据处理程序
        public void OnDgramPacketReceived(IPEndPoint remoteEP, String content)
        {
            textBoxRecords.Invoke(new Action(() =>
            {
                textBoxRecords.AppendText("来自:" + remoteEP.Address.ToString() + " 内容:" + content + "\r\n");
            }));
        }

        // 实现 IDgramPacketHandler 接口,心跳包数据处理程序
        public void OnDgramPacketReceived(IPEndPoint remoteEP, Byte[] content)
        {
            // 二进制数据接收处理程序
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 列举本机所有的有效IP地址(自动过滤掉虚拟网卡IP地址)
            String[] IPCollection = GetLocalIPv4Address();
            if (IPCollection != null)
            {
                comboBoxServerIP.DataSource = IPCollection;
                comboBoxServerIP.Enabled = !(IPCollection.Length == 1);  // 如果本机只有一个有效IP地址,则直接锁定
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (UdpServer != null) { UdpServer.Close(); UdpServer = null; }
        }

        /// <summary>
        /// 获取本机IP地址列表
        /// </summary>
        /// <param name="isIncludeUsb">是否包含USB网卡,默认为不包含</param>
        /// <returns>本机真实网卡信息</returns>
        public static String[] GetLocalIPv4Address(Boolean isIncludeUsb = false)
        {   // IPv4正则表达式
            const String IPv4RegularExpression = "^(?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))$";

            // 注意:只获取已连接的网卡
            String NetworkAdapterQueryString;
            if (isIncludeUsb)
                NetworkAdapterQueryString = "SELECT * FROM Win32_NetworkAdapter WHERE (NetConnectionStatus = 2) AND (MACAddress IS NOT NULL) AND (NOT (PNPDeviceID LIKE 'ROOT%'))";
            else
                NetworkAdapterQueryString = "SELECT * FROM Win32_NetworkAdapter WHERE (NetConnectionStatus = 2) AND (MACAddress IS NOT NULL) AND (NOT (PNPDeviceID LIKE 'ROOT%')) AND (NOT (PNPDeviceID LIKE 'USB%'))";

            ManagementObjectCollection NetworkAdapterQueryCollection = new ManagementObjectSearcher(NetworkAdapterQueryString).Get();
            if (NetworkAdapterQueryCollection == null) return null;

            List<String> IPv4AddressList = new List<String>(NetworkAdapterQueryCollection.Count);
            foreach (ManagementObject mo in NetworkAdapterQueryCollection)
            {
                // 获取网卡配置信息
                String ConfigurationQueryString = "SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Index = " + mo["Index"];
                ManagementObjectCollection ConfigurationQueryCollection = new ManagementObjectSearcher(ConfigurationQueryString).Get();
                if (ConfigurationQueryCollection == null) continue;

                foreach (ManagementObject nacmo in ConfigurationQueryCollection)
                {
                    if ((Boolean)nacmo["IPEnabled"])
                    {
                        String[] IPCollection = nacmo["IPAddress"] as String[]; // IP地址
                        if (IPCollection != null)
                        {
                            foreach (String adress in IPCollection)
                            {
                                Match match = Regex.Match(adress, IPv4RegularExpression);
                                if (match.Success) { IPv4AddressList.Add(adress); break; }
                            }
                        }
                    }
                }
            }

            if (IPv4AddressList.Count > 0) return IPv4AddressList.ToArray(); else return null;
        }
    }
}

Comments are closed.