好吧,我想我现在已经 100% 工作了!这是代码,欢迎任何批评,这是我第一次尝试 c#,主要来自 JS 背景。最终使用 thread.abort,不确定这是否是结束此问题的最佳方式。我也输入了一个 _shouldStop 布尔值。
public partial class TimeReporterService : ServiceBase
{
private Thread worker = null;
private bool _shouldStop = false;
public TimeReporterService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
_shouldStop = false;
worker = new Thread(SimpleListenerExample);
worker.Name = "Time Reporter";
worker.IsBackground = false;
worker.Start();
}
protected override void OnStop()
{
_shouldStop = true;
worker.Abort();
}
void SimpleListenerExample()
{
string[] prefixes = new[] { "http://*:12227/" };
// URI prefixes are required,
// for example "http://contoso.com:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
while (!_shouldStop)
{
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "{\"systemtime\":\"" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\"}";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
}
listener.Stop();
}
}