WebServer.cs
1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using ConfigHelper;
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);
Config.Set("Addr", 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服务已关闭");
}
}
}