Mina.NET:汉王人脸通SDK示例代码(三)接收卡点数据

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

添加引用:

演示程序界面
MinaTcpServerDemo

源代码
MinaTcpServerForm.cs

/* ----------------------------------------------------------
 * 文件名称:MinaTcpServerForm.cs
 * 
 * 作者:秦建辉
 * 
 * QQ:36748897
 * 
 * 博客:http://www.firstsolver.com/wordpress/
 * 
 * 开发环境:
 *      Visual Studio 2015
 *      .NET Framework 4 Client Profile
 *      
 * 版本历史:
 *      V1.0    2016年01月10日
 *              基于Mina.NET框架的Tcp服务器端演示
 *
 * 参考资料:
 *      http://git.oschina.net/longshine/Mina.NET
------------------------------------------------------------ */
using Com.FirstSolver.FaceId;
using Mina.Core.Session;
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
    {
        // 序列号属性键
        private static readonly AttributeKey KEY_SERIALNUMBER = new AttributeKey(typeof(MinaTcpServerForm), "SerialNumber");

        /// <summary>
        /// 设备通信字符集代码页为简体中文
        /// </summary>           
        private const Int32 DeviceCodePage = 936;

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

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

        public MinaTcpServerForm()
        {
            InitializeComponent();
        }

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

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

                IsServerRunning = false;
                buttonStart.Text = "开启侦听";
            }
            else
            {   // 通信密钥
                string SecretKey = textBoxSecretKey.Text;

                // 开启侦听
                TcpServer = new AsyncSocketAcceptor();
                TcpServer.FilterChain.AddLast("codec", new ProtocolCodecFilter(new FaceIdProtocolCodecFactory(DeviceCodePage)));

                // 设置事件处理器
                TcpServer.SessionOpened += (o, ea) =>
                {   // 每个Session可以有独立的通信密钥
                    if (!String.IsNullOrEmpty(SecretKey))
                    {   // 设置通信密钥
                        FaceIdProtocolCodecFactory.SetEncoderKey(ea.Session, SecretKey);
                        FaceIdProtocolCodecFactory.SetDecoderKey(ea.Session, SecretKey);
                    }
                };

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

                    if (Message.StartsWith("PostRecord"))
                    {   // 提取序列号并保存
                        string SerialNumber = FaceId_Item.GetKeyValue(Message, "sn");
                        ea.Session.SetAttribute(KEY_SERIALNUMBER, SerialNumber);
                                                
                        // 答复已准备好接收考勤记录,并且告知不需要上传照片
                        ea.Session.Write("Return(result=\"success\" postphoto=\"false\")");
                    }
                    else if (Message.StartsWith("Record"))
                    {   // 获取设备序列号
                        string SerialNumber = (string)ea.Session.GetAttribute(KEY_SERIALNUMBER);

                        // 处理卡点数据

                        // 服务器回应
                        ea.Session.Write("Return(result=\"success\")");   // 答复数据接收成功
                    }
                    else if (Message.StartsWith("PostEmployee"))
                    {   // 准备上传人员
                        ea.Session.Write("Return(result=\"success\")");
                    }
                    else if (Message.StartsWith("Employee"))
                    {   // 处理人员数据

                        // 服务器回应
                        ea.Session.Write("Return(result=\"success\")");   // 答复数据接收成功
                    }
                    else if (Message.StartsWith("GetRequest"))
                    {   // 模拟命令下发
                        ea.Session.Write("GetDeviceInfo()");   // 下发命令:获取设备信息
                    }
                    else if (Message.StartsWith("Quit"))
                    {   // 连接断开
                        ea.Session.Close(true);
                    }
                };

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

                    ea.Session.Close(true);
                };

                // 绑定侦听端口,开始侦听
                TcpServer.Bind(new IPEndPoint(IPAddress.Parse(comboBoxServerIP.Text), Int32.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地址,则直接锁定
            }
        }

        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(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.