You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

110 lines
2.8 KiB

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Net;
namespace Apewer.Web
{
/// <summary></summary>
public class Listener
{
private HttpListener _listener;
private Thread _thread;
private int _port = 80;
private string _ip = "127.0.0.1";
/// <summary></summary>
public Action<HttpListenerContext> Action { get; set; }
/// <summary></summary>
public string IP
{
get { return _ip; }
set { _ip = NetworkUtility.IsIP(value) ? value : "127.0.0.1"; }
}
/// <summary></summary>
public int Port
{
get { return _port; }
set { _port = Math.Max(ushort.MinValue, Math.Min(ushort.MaxValue, value)); }
}
/// <summary></summary>
public Exception Start()
{
var prefix = $"http://{_ip}:{Port}/";
Logger.Web.Info(this, $"准备在 {prefix} 启动。");
_listener = new HttpListener();
try
{
_listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
_listener.Prefixes.Add(prefix);
_listener.Start();
// 多线程方式处理请求。
// _thread = new Thread(Listen);
// _thread.IsBackground = true;
// _thread.Start();
// 异步方式处理请求。
_listener.BeginGetContext(Received, null);
Logger.Web.Info(this, $"已在 {prefix} 启动。");
return null;
}
catch (Exception ex)
{
Logger.Web.Exception(this, ex);
Logger.Web.Info(this, $"在 {prefix} 启动失败。");
return ex;
}
}
/// <summary></summary>
public void Stop()
{
if (_thread != null)
{
// _thread.Abort();
_thread = null;
}
if (_listener != null)
{
_listener.Close();
_listener.Stop();
_listener = null;
}
}
void Received(IAsyncResult ar)
{
_listener.BeginGetContext(Received, null);
var context = _listener.EndGetContext(ar);
var action = Action;
if (action != null) action(context);
}
void Listen()
{
while (true)
{
if (_listener == null) break;
var context = _listener.GetContext();
var action = Action;
if (action == null) continue;
action(context);
// RuntimeUtility.InBackground(() => action(context), true);
}
}
}
}