gpt4 book ai didi

c# - HttpListener 处理多个请求

转载 作者:可可西里 更新时间:2023-11-01 17:09:09 28 4
gpt4 key购买 nike

<分区>

我有这个 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);


}

}

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com