Apache Thrift(二)构建汉字拼音查询微服务:服务器端

同系列文章:

源代码下载

MandarinThrift 20170717.zip

演示程序界面

源代码
TcpServerParams.cs

using System.Net;

namespace Splash
{
    public class TcpServerParams
    {
        /// <summary>
        /// 接收服务器地址
        /// </summary>
        public IPAddress ServerIP;

        /// <summary>
        /// 接收服务器端口
        /// </summary>
        public int ServerPort;
    }
}

MandarinThriftServerForm.cs

/* ----------------------------------------------------------
 * 文件名称:MandarinThriftServerForm.cs
 * 
 * 作者:秦建辉
 * 
 * 微信:splashcn
 * 
 * 博客:http://www.firstsolver.com/wordpress/
 * 
 * 开发环境:
 *      Visual Studio 2017
 *      .NET Framework 4.5.2
 *      Apache Thrift v0.10.0
 *      
 * 版本历史:
 *      V1.0    2017年07月16日
 *              基于Thrift框架实现汉字拼音查询服务-服务器端
 *
 * 参考资料:
 *      http://thrift.apache.org
------------------------------------------------------------ */
using Com.FirstSolver.Mandarin.Thrift;
using System;
using System.Collections.Generic;
using System.Management;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using Thrift.Server;
using Thrift.Transport;

namespace Splash
{
    public partial class MandarinThriftServerForm : Form
    {
        /// <summary>
        /// 服务线程
        /// </summary>
        private Thread ServiceThread = null;

        /// <summary>
        /// Thrift Server
        /// </summary>
        private TServer ServiceServer;

        public MandarinThriftServerForm()
        {
            InitializeComponent();
        }

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

        private void buttonService_Click(object sender, EventArgs e)
        {
            if (ServiceThread != null)
            {
                buttonService.Enabled = false;
                ThreadPool.QueueUserWorkItem(StopServiceServer);
            }
            else
            {
                try
                {
                    IPAddress ServerIP = IPAddress.Parse(comboBoxServerIP.Text); // 服务器地址
                    int ServerPort = int.Parse(textBoxServerPort.Text); // 服务器端口 

                    // 线程池任务
                    ThreadPool.QueueUserWorkItem(StartServiceServer,
                        new TcpServerParams()
                        {
                            ServerIP = ServerIP,
                            ServerPort = ServerPort,
                        });
                }
                catch (Exception exception)
                {
                    AppendLog("Exception: " + exception.Message);
                }
            }
        }

        // 开启服务
        private void StartServiceServer(object state)
        {
            TcpServerParams Args = state as TcpServerParams;
            try
            {
                TcpListener Listener = new TcpListener(Args.ServerIP, Args.ServerPort);

                MandarinServiceHandler handler = new MandarinServiceHandler();
                MandarinService.Processor processor = new MandarinService.Processor(handler);

                TServerTransport serverTransport = new TServerSocket(Listener);
                ServiceServer = new TThreadPoolServer(processor, serverTransport);

                ServiceThread = Thread.CurrentThread;
                SetStatus(true);

                ServiceServer.Serve();
            }
            catch (Exception exception)
            {
                AppendLog(exception.Message);
            }
            finally
            {
                SetStatus(false);
                ServiceThread = null;
            }
        }

        // 停止服务
        private void StopServiceServer(object state)
        {
            ServiceServer.Stop();
            ServiceThread.Join();
        }

        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)
        {
            // 线程池线程自动关闭
        }

        public void AppendLog(string text)
        {
            this.BeginInvoke(new Action<string>((msg) =>
            {
                this.listBoxQuery.Items.Add(msg);
            }), text);
        }

        public void SetStatus(bool isServerRunning)
        {
            this.BeginInvoke(new Action<bool>((status) =>
            {
                if (status)
                {
                    AppendLog("服务已启动!");
                    this.buttonService.Text = "停止服务";
                }
                else
                {
                    AppendLog("服务已停止!");
                    this.buttonService.Text = "开启服务";
                    this.buttonService.Enabled = true;
                }
            }), isServerRunning);
        }

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