WebService.cs
2.0 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
62
63
64
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服务已关闭");
}
}
}