C#:汉王人证通/人脸仪数据接收示例

同系列文章

演示程序界面

源代码
MinaTcpServerForm.cs

/* ----------------------------------------------------------
 * 文件名称:MinaTcpServerForm.cs
 * 
 * 作者:秦建辉
 * 
 * 微信:splashcn
 * 
 * 博客:http://www.firstsolver.com/wordpress/
 * 
 * 开发环境:
 *      Visual Studio 2017
 *      .NET Framework 4 Client Profile
 *      
 * 版本历史:
 *      V1.0    2017年12月04日
 *              汉王人证通/人脸仪通信SDK-服务器端数据接收演示示例
 *
 * 参考资料:
 *      https://mina.codeplex.com/
 *      http://git.oschina.net/longshine/Mina.NET
------------------------------------------------------------ */
using Com.FirstSolver.Splash;
using Mina.Filter.Codec;
using Mina.Transport.Socket;
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 MinaTcpServerForm : Form
    {
        /// <summary>
        /// 用于密钥交换的服务器端证书
        /// </summary>
        private SM2UserInformation SM2ServerInfo = new SM2UserInformation(
            "Com.FirstSolver.Splash",
            "DE078F1052116A4F706288AB9EC8E10009EAA510B68B68D917AA63F3D07B3876",
            "59C9ADD36106ABD5D26CCF7F92D8BBAD33A0C55D0CF9F644CF97D340EDDFB949",
            "D781D3BBD4F1B8263DBF68613CF7E830BBD6CC569740303D4DDEAEB5216AE639"
            );

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

        /// <summary>
        /// 侦听服务器
        /// </summary>
        private AsyncSocketAcceptor TcpServer = null;

        public MinaTcpServerForm()
        {
            InitializeComponent();
        }

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

        private void buttonStart_Click(object sender, EventArgs e)
        {
            if (IsServerRunning)
            {   // 停止侦听
                if (TcpServer != null)
                {
                    TcpServer.Dispose();
                    TcpServer = null;
                }

                IsServerRunning = false;
                buttonStart.Text = "开启侦听";
            }
            else
            {
                // 开启侦听
                TcpServer = new AsyncSocketAcceptor();
                TcpServer.FilterChain.AddLast("codec", new ProtocolCodecFilter(new FaceReaderProtocolCodecFactory(checkBoxPassiveEncryption.Checked, null)));

                TcpServer.SessionOpened += (o, ea) =>
                {
                    FaceReaderProtocolCodecFactory.EnablePassiveEncryption(ea.Session, true, SM2ServerInfo);
                };

                TcpServer.MessageReceived += (o, ea) =>
                {   // 显示接收字符串
                    string Message = (string)ea.Message;
                    this.Invoke(new Action(() => {
                        textBoxAnswer.AppendText(Message + "\r\n");
                    }));

                    COMMAND_PCIR_TYPE A = Message.FromJsonTo<COMMAND_PCIR_TYPE>();
                    if (string.Equals(A.COMMAND, "RecogniseResult"))
                    {
                        // 注意:保存数据然后进行回复
                        REPLY_PCIR_TYPE M = new REPLY_PCIR_TYPE();
                        M.RETURN = "RecogniseResult";
                        M.PARAM = new PARAM_REPLY_PCIR_TYPE();
                        M.PARAM.result = "success";
                        ea.Session.Write(M.ToJsonString());
                    }
                };

                TcpServer.ExceptionCaught += (o, ea) =>
                {   // 线程安全性
                    textBoxAnswer.Invoke(new Action(() =>
                    {
                        textBoxAnswer.AppendText("Exception: " + ea.Exception.Message.ToString() + "\r\n");
                    }));

                    ea.Session.Close(true);
                };

                // 绑定侦听端口,开始侦听
                TcpServer.Bind(new IPEndPoint(IPAddress.Parse(comboBoxServerIP.Text), int.Parse(textBoxServerPort.Text)));

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

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

            textBoxAnswer.MaxLength = 0;
        }

        private void MinaTcpServerForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (TcpServer != null)
            {
                TcpServer.Dispose();
                TcpServer = null;
            }
        }

        /// <summary>
        /// 获取本机IP地址列表
        /// </summary>
        /// <param name="isIncludeUsb">是否包含USB网卡,默认为不包含</param>
        /// <returns>本机真实网卡信息</returns>
        public static string[] GetLocalIPv4Address(bool 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 ((bool)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.