我必须建立一个HttpListener,它将等待客户端服务器的请求。我必须在端口8088上接收该请求,并提取查询字符串。这是最简单的部分。
我正在windows服务中运行HttpListener。我不能让它正常发射。我构建安装项目,在我们的服务器上安装服务,它永远不会启动。我怀疑我的代码有错误。
HttpListenerClass:
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);
}
}
}
}Service1.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();
}
}
}我做错了什么?
谢谢你们!
发布于 2011-03-30 12:00:08
在while(true)循环中排队工作项?你肯定?!
OnStart循环的存在,您的while方法永远不会返回。但是,从OnStart方法返回是服务管理器必须知道的,您的服务启动是正确的。OutOfMemoryException或类似的东西一起消亡。建议:
尝试采用这个样本。它在IronPython中,但也使用.NET框架。提示:应该更改该实现中的while(true),以便在服务停止时能够中断while循环。此外,必须以异步方式在serveforever方法中调用Start。
这应该能让你走了。
https://stackoverflow.com/questions/5485951
复制相似问题