我有这个 HttpListener,它非常适合单个请求,但在完成请求后它会关闭。我感兴趣的是一个监听器,它保持与客户端的连接,直到指定的 URL 中不再有文件为止。我尝试过摆弄线程和异步调用,但到目前为止我还没有能够让它发挥任何作用。我只是很难想象没有一些相对简单的方法可以让 HttpListener 保持连接而不是在完成每个请求后关闭。
public static void Listener(string[] prefixes)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
return;
}
// URI prefixes are required,
// for example "http://contoso.com:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add("http://" + s + "/");
}
listener.Start();
Console.WriteLine("\nListening...");
HttpListenerContext context = listener.GetContext();
Console.WriteLine("Request received...\n");
HttpListenerRequest request = context.Request;
// Obtain a response object.
string url = context.Request.RawUrl;
string[] split = url.Split('/');
int lastIndex = split.Length - 1;
int x, y, z;
x = Convert.ToInt32(split[lastIndex]);
y = Convert.ToInt32(split[lastIndex - 1]);
z = Convert.ToInt32(split[lastIndex - 2]);
HttpListenerResponse response = context.Response;
#region Load image and respond
// Load the image
Bitmap bm = new Bitmap("C:\\MyFolder\\image_1\\");
MemoryStream bmStream = new MemoryStream();
bm.Save(bmStream, ImageFormat.Png);
byte[] buffer = bmStream.ToArray();
// Get a response stream and write the response to it.
response.ContentLength64 = bmStream.Length;
response.ContentType = "image/png";
response.KeepAlive = true;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
// You must close the output stream.
output.Close();
listener.Stop();
#endregion
这是程序:
class Program
{
static void Main(string[] args)
{
string name = (args.Length < 1) ? Dns.GetHostName() : args[0];
try
{ //Find the IPv4 address
IPAddress[] addrs = Array.FindAll(Dns.GetHostEntry(string.Empty).AddressList,
a => a.AddressFamily == AddressFamily.InterNetwork);
Console.WriteLine("Your IP address is: ");
foreach (IPAddress addr in addrs)
Console.WriteLine("{0} {1}", name, addr);
//Automatically set the IP address
string[] ips = addrs.Select(ip => ip.ToString()).ToArray();
Response.Listener(ips);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
//Manually setting the IP - not optimal!
//string[] ipstring = new string[1] { "10.10.180.11:8080" };
//Response.Listener(ipstring);
}
}
最佳答案
是的 - 您正在调用 GetContext
一次,满足该请求,然后停止。
相反,您应该调用 GetContext
循环中。根据您是否希望能够同时处理多个请求,您可能有 GetContext
在一个线程中,然后将每个请求交给一个单独的(可能是线程池)线程来响应它。
稍微棘手的一点是关闭 - 如果您想要彻底关闭,您需要确定何时停止循环(以及如果您正在 GetContext
通话中该怎么办),并等待未完成的请求完成。
关于c# - 处理多个请求的 HttpListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26507645/