1. 程式人生 > >windows服務中對外提供API接口

windows服務中對外提供API接口

ati system msg odin err protect nco res fix

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接口