我有这个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);
}
}
答案 0 :(得分:2)
是的 - 您正在呼叫GetContext
一次,提供该请求,然后停止。
相反,您应该在循环中调用GetContext
。根据您是否希望能够同时处理多个请求,您可能在一个线程中有GetContext
,然后将每个请求移交给一个单独的(可能是线程池)线程来响应它。 / p>
稍微棘手的一点是关闭 - 如果你想要一个干净的关机,你需要找出什么时候停止循环(以及如果你正处于GetContext
电话中间该怎么办),等待未完成的请求完成。
答案 1 :(得分:0)
处理完一个请求后会停止侦听,因为您只是停止侦听。你需要实现类似等待循环的东西。
可以在codeproject - example找到帮助您的示例。
注意代码的这一部分以及如何在示例中使用它:
private void startlistener(object s)
{
while (true)
{
////blocks until a client has connected to the server
ProcessRequest();
}
}