我必須建立一個HttpListener
,它將等待客戶端服務器發出的請求。我必須在端口8088上接收該請求並提取查詢字符串。這是很容易的部分。HttpListener問題
我在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();
}
}
}
我在做什麼錯?
謝謝你們!
查看事件日誌併發布您在此處看到的錯誤。 – Aliostad 2011-03-30 11:59:03
當你說「永不開始」,你能更具體嗎?你打算怎麼開始它?它是否因錯誤而失敗?該錯誤是否在控制檯或事件查看器中可見?也許把所有的東西都包裝在try/catch中,並在任何地方寫出任何異常來看看是否能夠解決這個問題? – David 2011-03-30 12:01:12
當兩個線程同時進入AddToFile()方法時,會發生什麼情況會非常令人興奮。 ;) – 2011-03-30 12:44:04