WebService.cs 2.0 KB
using BLL;
using Microsoft.Win32;
using System;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace SmartScan
{
    public static class WebService
    {
        private static WebServiceHost _serviceHost;

        public static bool IsOpen { private set; get; }
        static int errcount = 0;
        public static void Open(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                Model.LogNet.log.Info("WebService没有配置,不开启");
                return;
            }
            var u = new Uri(url);
            try
            {
                WebCallWork service = new();
                _serviceHost = new(service, u);
                _serviceHost.Open();
                Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\NS100\\", "port", u.Port);
                Registry.SetValue("HKEY_CURRENT_USER\\SOFTWARE\\NS100\\", "port", u.Port);
                Model.LogNet.log.Info("Web服务已开启,URL=" + url);
                IsOpen = true;
            }
            catch (AddressAlreadyInUseException ex)
            {
                Model.LogNet.log.Info("端口:" + u.Port + " 被占用");
                errcount++;
                if (errcount > 20)
                {
                    Environment.Exit(99);
                    return;
                }
                Random a = new Random((int)DateTime.Now.Ticks);
                var nu = "http://0.0.0.0:" + a.Next(40000, 60000) + "/";
                Open(nu);
            }
            catch (Exception ex)
            {
                Model.LogNet.log.Error("Open", ex);
                IsOpen = false;
            }
        }

        public static void Close()
        {
            if (_serviceHost != null)
            {
                if (_serviceHost.State != System.ServiceModel.CommunicationState.Faulted)
                    _serviceHost.Close();
            }
            Model.LogNet.log.Info("Web服务已关闭");
        }
    }

}