This commit is contained in:
ChsBuffer
2021-02-20 18:15:16 +08:00
parent 021f940957
commit ac0800ec56
79 changed files with 924 additions and 890 deletions

View File

@@ -8,7 +8,7 @@ namespace Netch.Utils.HttpProxyHandler
public class HttpWebServer
{
private HttpListener _listener;
private Func<HttpListenerRequest, string> _responderMethod;
private readonly Func<HttpListenerRequest, string> _responderMethod;
public HttpWebServer(string[] prefixes, Func<HttpListenerRequest, string> method)
{
@@ -17,8 +17,7 @@ namespace Netch.Utils.HttpProxyHandler
_listener = new HttpListener();
if (!HttpListener.IsSupported)
throw new NotSupportedException(
"Needs Windows XP SP2, Server 2003 or later.");
throw new NotSupportedException("Needs Windows XP SP2, Server 2003 or later.");
// URI prefixes are required, for example
// "http://localhost:8080/index/".
@@ -29,7 +28,7 @@ namespace Netch.Utils.HttpProxyHandler
if (method == null)
throw new ArgumentException("method");
foreach (string s in prefixes)
foreach (var s in prefixes)
_listener.Prefixes.Add(s);
_responderMethod = method;
@@ -41,42 +40,40 @@ namespace Netch.Utils.HttpProxyHandler
}
}
public HttpWebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
: this(prefixes, method)
public HttpWebServer(Func<HttpListenerRequest, string> method, params string[] prefixes) : this(prefixes, method)
{
}
public void Run()
{
ThreadPool.QueueUserWorkItem((o) =>
ThreadPool.QueueUserWorkItem(o =>
{
Logging.Info("Webserver running...");
try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem((c) =>
{
var ctx = c as HttpListenerContext;
try
ThreadPool.QueueUserWorkItem(c =>
{
string rstr = _responderMethod(ctx.Request);
byte[] buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.StatusCode = 200;
ctx.Response.ContentType = "application/x-ns-proxy-autoconfig";
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
}
catch
{
} // suppress any exceptions
finally
{
// always close the stream
ctx.Response.OutputStream.Close();
}
}, _listener.GetContext());
}
var ctx = c as HttpListenerContext;
try
{
var rstr = _responderMethod(ctx.Request);
var buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.StatusCode = 200;
ctx.Response.ContentType = "application/x-ns-proxy-autoconfig";
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
}
catch
{
} // suppress any exceptions
finally
{
// always close the stream
ctx.Response.OutputStream.Close();
}
},
_listener.GetContext());
}
catch (Exception ex)
{