![](/img/trans.png)
[英]HttpListener in mono can't process more than 2 requests in the same time?
[英]An alive httplistener that can handle and response more than 100 request at the same time
我需要创建“一个可以同时处理和响应100多个请求的活动httplistener” 。
好的,目前我正在为我的应用程序使用tcplistener和websockets ,但是如您所知,它们在客户端和服务器之间创建了双工和连接连接。
对于我的应用程序的一部分,我需要一个类似php的,类似于 Http的连接系统,我的意思是一个请求>一个响应 。
现在,我需要在服务器上的单独进程上使用httplistener 。
但是问题是:
我已经阅读以下主题:
在C#(.net)下具有HTTP服务器的Keep-Alive套接字如何发送几个查询?
还没工作... :(
我该如何运作?
回答: 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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.