WebServer.cs 1.8 KB
using Microsoft.Win32;
using System;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Windows.Forms;

namespace ScanCodeServer
{
    public static class WebServer
    {
        private static WebServiceHost _serviceHost;

        public static bool IsOpen { private set; get; }
        static WebWork service = new WebWork();
        static int errcount = 0;
        public static void Open(string url)
        {
            var u = new Uri(url);
            try
            {
                _serviceHost = new WebServiceHost(service, u);
                _serviceHost.Open();
                Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\ScanCodeServer\\", "port", u.Port);
                Common.log.Info("Web服务已开启,URL=" + url);
                IsOpen = true;
            }
            catch (AddressAlreadyInUseException ex)
            {
                Common.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)
            {
                Common.log.Error("WebService Open", ex);
                IsOpen = false;
                Environment.Exit(98);
            }
        }

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

}