码迷,mamicode.com
首页 > Windows程序 > 详细

windows服务中对外提供API接口

时间:2018-08-21 17:17:24      阅读:1904      评论:0      收藏:0      [点我收藏+]

标签:启动   obj   其他   empty   star   adp   发送   byte   encoding   

public class SendMqService
{
        private static bool isExcute = true;
        private static HttpListener listener = new HttpListener();
        public static void Start()
        {
            System.Threading.ThreadPool.QueueUserWorkItem(w => Excute());//单独开启一个线程执行监听消息
        }

        private static void Excute()
        {
            if (HttpListener.IsSupported)
            {
                if (!listener.IsListening)
                {
                    listener.Prefixes.Add(AppSetingHelper.GetValue("SendMqAddress")); //添加需要监听的url,如:http://192.016.0.1:8888
                    listener.Start(); //开始监听端口,接收客户端请求
                }
                while (isExcute)
                {
                    try
                    {
                        //阻塞主函数至接收到一个客户端请求为止
                        HttpListenerContext context = listener.GetContext();
                        HttpListenerRequest request = context.Request;
                        HttpListenerResponse response = context.Response;

                        var reader = new StreamReader(request.InputStream);
                        var mqMsg = reader.ReadToEnd();
                        var responseString = string.Empty;

              // 执行其他业务逻辑
              //*****************
                        
                        responseString = JsonConvert.SerializeObject(new { code = 0, msg = "发送成功" });                       
                        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                        //对客户端输出相应信息.
                        response.ContentLength64 = buffer.Length;
                        using (System.IO.Stream output = response.OutputStream)
                        {
                            output.Write(buffer, 0, buffer.Length);
                        }
                    }
                    catch (Exception exceotion)
                    {
                        Logger.Error("处理消息异常", exceotion);
                    }
                }
            }
            else
            {
                Logger.Info("系统不支持HttpListener");
            }            
        }

        public static void Stop()
        {
            isExcute = false;
            if (listener.IsListening)
                listener.Stop();
        }
    }
}

服务启动时需要启动监听,服务停止时需要停止监听

        protected override void OnStart(string[] args)
        {
            SendMqService.Start();
        }

        protected override void OnStop()
        {
            //停止监听
            SendMqService.Stop();
        }

 

windows服务中对外提供API接口

标签:启动   obj   其他   empty   star   adp   发送   byte   encoding   

原文地址:https://www.cnblogs.com/pudefu/p/9512326.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!