我必须建立一个 HttpListener
来等待客户端服务器发出的请求。我必须在端口 8088 上接收该请求并提取查询字符串。这是简单的部分。
我在 Windows 服务中运行 HttpListener
。我无法让它正常开火。我构建了安装项目,在我们的服务器上安装了服务,但它从未启动。我怀疑我的代码有问题。
HttpListener类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Threading;
namespace lalalolo
{
class HttpListenerClass
{
bool keepAlive = true;
public void AddToFile(string contents)
{
var fs = new FileStream(@"C:\HttpListenerserv.txt", FileMode.OpenOrCreate, FileAccess.Write);
var sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine(contents);
sw.Flush();
sw.Close();
}
private HttpListener listener;
public HttpListenerClass()
{
ThreadPool.SetMaxThreads(50, 100);
ThreadPool.SetMinThreads(50, 50);
listener = new HttpListener();
listener.Prefixes.Add("http://*:8088/");
}
public void Start()
{
listener.Start();
if(keepalive == true){
{
try
{
HttpListenerContext ctx = listener.GetContext();
ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessRequest), ctx);
}
catch(Exception ex)
{
AddToFile(ex.Message);
}
}
}
}
public void Stop()
{
listener.Stop();
keepalive == false;
}
public void ProcessRequest(object listenerContext)
{
try
{
var context = (HttpListenerContext)listenerContext;
string QS = context.Request.QueryString["ID"];
AddToFile(QS);
}
catch(Exception ex)
{
AddToFile(ex.Message);
}
}
}
}
服务1.cs:
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading;
namespace lalalolo
{
public partial class HttpListenerTest1 : ServiceBase
{
HttpListenerClass HTTP = new HttpListenerClass();
public void AddToFile(string contents)
{
var fs = new FileStream(@"C:\HttpListenerserv.txt", FileMode.OpenOrCreate, FileAccess.Write);
var sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine(contents);
sw.Flush();
sw.Close();
}
public HttpListenerTest1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
HTTP.Start();
}
protected override void OnStop()
{
HTTP.Stop();
}
}
}
我做错了什么?
谢谢大家!
最佳答案
在 while(true)
循环中排队工作项?你是认真的?!
- 由于
while
循环,您的OnStart
方法永远不会返回。但是,从OnStart
方法返回对于服务经理来说至关重要,因为您的服务已正确启动。 - 由于无限循环,您的服务可能会因
OutOfMemoryException
或类似问题而终止。
建议:
尝试采用 this sample .它在 IronPython 中,但也使用 .NET 框架。提示:应该更改该实现中的 while(true)
以便在您的服务停止时能够中断 while 循环。此外,您必须以异步方式在 Start
方法中调用 serveforever
。
这应该让你继续。
关于c# - HttpListener 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5485951/