Skip to content

Commit

Permalink
添加对HttpServer类的错误处理委托
Browse files Browse the repository at this point in the history
防止插件无法启动监听时对ACT的连带刑
  • Loading branch information
Natsukage committed Oct 28, 2020
1 parent 412cc76 commit 1acc355
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
18 changes: 15 additions & 3 deletions PostNamazu/Common/HTTPServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,18 @@ namespace PostNamazu.Models
{
public delegate void ReceivedHttpCommandRequestEventHandler(string command);
public delegate void ReceivedHttpWayMarksRequestEventHandler(string waymarkJson);
public delegate void OnExceptionEventHandler(Exception ex);

internal class HttpServer
{
private Thread _serverThread;
private HttpListener _listener;
SynchronizationContext ui = SynchronizationContext.Current;
public int Port { get; private set; }

public event ReceivedHttpCommandRequestEventHandler ReceivedCommandRequest;
public event ReceivedHttpWayMarksRequestEventHandler ReceivedWayMarksRequest;
public event OnExceptionEventHandler OnException;

/// <summary>
/// 在指定端口启动监听
Expand Down Expand Up @@ -53,9 +56,18 @@ public void Stop()

private void Listen()
{
_listener = new HttpListener();
_listener.Prefixes.Add("http://*:" + Port + "/");
_listener.Start();
try
{
_listener = new HttpListener();
_listener.Prefixes.Add("http://*:" + Port + "/");
_listener.Start();
}
catch (Exception ex)
{
OnException?.Invoke(ex);
return;
}


ThreadPool.QueueUserWorkItem(o =>
{
Expand Down
19 changes: 18 additions & 1 deletion PostNamazu/PostNamazu.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,15 @@ private void ServerStart(object sender = null, EventArgs e = null)
_httpServer = new HttpServer((int) PluginUI.TextPort.Value);
_httpServer.ReceivedCommandRequest += DoTextCommand;
_httpServer.ReceivedWayMarksRequest += DoWaymarks;
_httpServer.OnException += OnException;

PluginUI.ButtonStart.Enabled = false;
PluginUI.ButtonStop.Enabled = true;
PluginUI.Log($"在{_httpServer.Port}端口启动监听");
}
catch (Exception ex)
{
PluginUI.Log($"无法在{_httpServer.Port}端口启动监听\n{ex.Message}");
OnException(ex);
}
}

Expand All @@ -92,11 +93,27 @@ private void ServerStop(object sender = null, EventArgs e = null)
_httpServer.Stop();
_httpServer.ReceivedCommandRequest -= DoTextCommand;
_httpServer.ReceivedWayMarksRequest -= DoWaymarks;
_httpServer.OnException -= OnException;

PluginUI.ButtonStart.Enabled = true;
PluginUI.ButtonStop.Enabled = false;
PluginUI.Log("已停止监听");
}
/// <summary>
/// 委托给HttpServer类的异常处理
/// </summary>
/// <param name="ex"></param>
private void OnException(Exception ex)
{
string errorMessage = $"无法在{_httpServer.Port}端口启动监听\n{ex.Message}";

PluginUI.ButtonStart.Enabled = true;
PluginUI.ButtonStop.Enabled = false;

PluginUI.Log(errorMessage);
MessageBox.Show(errorMessage);
}



/// <summary>
Expand Down

0 comments on commit 1acc355

Please sign in to comment.