我需要创建“一个可以同时处理和响应100多个请求的活着的httplistener”。
好,目前,我在应用程序中使用 tcplistener 和 websockets ,但是如您所知,它们在两个连接之间建立了一个双工且已连接的连接客户端和服务器。
对于我的应用程序的一部分,我需要一个类似于php ,类似于Http 的连接系统,我的意思是一个请求>一个响应 >。
现在,我需要在服务器上的单独进程上使用 httplistener 。
但是问题是:
我已经阅读了以下主题:
How does HttpListener handle KeepAllive
Handling multiple requests with C# HttpListener
Keep-Alive socket with HTTP server under C# (.net) how to send several queries?
httplistener connection keep alive possible?
HttpListener leaves connections in TIME_WAIT
尚不可用...:(
我如何使其正常工作?
答案 0 :(得分:0)
答案: https://codehosting.net/blog/BlogEngine/post/Simple-C-Web-Server
using System;
using System.Net;
using System.Threading;
using System.Linq;
using System.Text;
namespace WebServer
{
public class WebServer
{
private readonly HttpListener _listener = new HttpListener();
private readonly Func<HttpListenerRequest, string> _responderMethod;
public WebServer(string[] prefixes, Func<HttpListenerRequest, string> method)
{
if (!HttpListener.IsSupported)
throw new NotSupportedException(
"Needs Windows XP SP2, Server 2003 or later.");
// URI prefixes are required, for example
// "http://localhost:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
// A responder method is required
if (method == null)
throw new ArgumentException("method");
foreach (string s in prefixes)
_listener.Prefixes.Add(s);
_responderMethod = method;
_listener.Start();
}
public WebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
: this(prefixes, method) { }
public void Run()
{
ThreadPool.QueueUserWorkItem((o) =>
{
Console.WriteLine("Webserver running...");
try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem((c) =>
{
var ctx = c as HttpListenerContext;
try
{
string rstr = _responderMethod(ctx.Request);
byte[] buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
}
catch { } // suppress any exceptions
finally
{
// always close the stream
ctx.Response.OutputStream.Close();
}
}, _listener.GetContext());
}
}
catch { } // suppress any exceptions
});
}
public void Stop()
{
_listener.Stop();
_listener.Close();
}
}
}