windows服务中对外提供API接口

2021-07-15 12:13

阅读:409

标签:启动   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


评论


亲,登录后才可以留言!