注意:代码仅供参考,需要根据具体的设备做调整
同系列文章:
添加引用:
- MinaFaceIdCodec.dll
- Mina.NET.dll
演示程序界面
源代码
MinaUdpServerForm.cs
/* ---------------------------------------------------------- * 文件名称:MinaUdpServerForm.cs * * 作者:秦建辉 * * QQ:36748897 * * 博客:http://www.firstsolver.com/wordpress/ * * 开发环境: * Visual Studio 2015 * .NET Framework 4 Client Profile * * 版本历史: * V1.0 2016年01月10日 * 基于Mina.NET框架的Udp服务器端演示 * * 参考资料: * http://git.oschina.net/longshine/Mina.NET ------------------------------------------------------------ */ using Com.FirstSolver.FaceId; 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 MinaUdpServerForm : Form { /// <summary> /// 设备通信字符集代码页为简体中文 /// </summary> private const Int32 DeviceCodePage = 936; /// <summary> /// 服务器是否已运行 /// </summary> private Boolean IsServerRunning = false; /// <summary> /// 侦听服务器 /// </summary> private AsyncDatagramAcceptor UdpServer = null; public MinaUdpServerForm() { InitializeComponent(); } private void buttonClear_Click(object sender, EventArgs e) { textBoxRecords.Clear(); } private void buttonStart_Click(object sender, EventArgs e) { if (IsServerRunning) { // 停止侦听 if (UdpServer != null) { UdpServer.Dispose(); UdpServer = null; } IsServerRunning = false; buttonStart.Text = "开启侦听"; } else { // 开启侦听 UdpServer = new AsyncDatagramAcceptor(); UdpServer.FilterChain.AddLast("codec", new ProtocolCodecFilter(new FaceIdProtocolCodecFactory(DeviceCodePage))); UdpServer.SessionConfig.ReuseAddress = true; // 设置事件处理器 UdpServer.MessageReceived += (s, ea) => { // 显示接收字符串 string Message = (string)ea.Message; textBoxRecords.BeginInvoke(new Action(() => { textBoxRecords.AppendText(Message + "\r\n"); // 判断是否有命令下发 if (checkBoxTask.Checked) { // 通知设备有命令要发送 ea.Session.Write("PostRequest()"); } })); }; UdpServer.ExceptionCaught += (s, ea) => { // 线程安全性 textBoxRecords.BeginInvoke(new Action(() => { textBoxRecords.AppendText("Exception: " + ea.Exception.Message.ToString() + "\r\n"); })); ea.Session.Close(true); }; // 绑定侦听端口,开始侦听 UdpServer.Bind(new IPEndPoint(IPAddress.Parse(comboBoxServerIP.Text), Int32.Parse(textBoxServerPort.Text))); IsServerRunning = true; buttonStart.Text = "停止侦听"; } } private void MinaUdpServerForm_Load(object sender, EventArgs e) { // 列举本机所有的有效IP地址(自动过滤掉虚拟网卡IP地址) String[] IPCollection = GetLocalIPv4Address(); if (IPCollection != null) { comboBoxServerIP.DataSource = IPCollection; comboBoxServerIP.Enabled = !(IPCollection.Length == 1); // 如果本机只有一个有效IP地址,则直接锁定 } } private void MinaUdpServerForm_FormClosing(object sender, FormClosingEventArgs e) { if (UdpServer != null) { UdpServer.Dispose(); 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; } } }