HttpListener BeginGetContext突然停止
本文关键字:突然 BeginGetContext HttpListener | 更新日期: 2023-09-27 18:28:01
我有一个HttpListener,我不想在每次请求后关闭它,所以我使用BeginGetContext异步检索请求。只是工作不正常。
Main正确启动,为StartListening()函数查找并分配我的IP地址。然而,当我在StartListening()中到达listener.BeginGetContext(new AsyncCallback(OnRequest), listener);
时,它会跳到Main中的Response.StartListening(ips);
,然后停止。我不知道为什么。有什么提示吗?
这是我迄今为止所拥有的。
这就是我开始倾听请求的地方:
public static void StartListening(string[] prefixes)
{
HttpListener listener = new HttpListener();
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
foreach (string s in prefixes)
{
listener.Prefixes.Add("http://" + s + "/");
}
listener.Start();
Console.WriteLine("'nListening...");
listener.BeginGetContext(new AsyncCallback(OnRequest), listener);
}
这里是我处理请求的地方:
public static void OnRequest(IAsyncResult result)
{
HttpListener listener = (HttpListener) result.AsyncState;
HttpListenerContext context = listener.EndGetContext(result);
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;
Regex imageRegex = new Regex(@"SomethingSomething");
var matches = imageRegex.Match(url);
if (matches.Success)
{
string path = @"C:'SomeDir";
path = String.Format(path, matches.Groups[1].Captures[0],
matches.Groups[2].Captures[0],
matches.Groups[3].Captures[0]);
// Load the image
Bitmap bm = new Bitmap(path);
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;
Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
// You must close the output stream.
output.Close();
listener.Stop();
}
response.Close();
listener.BeginGetContext(new AsyncCallback(OnRequest), listener);
}
这是我的主要:
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.StartListening(ips);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
BeginGetContext
之后,它异步获取请求,因此不会阻塞调用线程(在本例中为主线程)。因为它没有阻止它,主线程结束,因此你的程序也结束了,因为它是主线程。
您可以通过使用ManualResetEvent
(在System.Threading
命名空间中)来修复此问题。这会阻塞主线程。
class Program
{
public static ManualResetEvent ServerManualResetEvent;
static void Main(string[] args)
{
try
{
// your code to start the server
ServerManualResetEvent = new ManualResetEvent(false);
ServerManualResetEvent.WaitOne();
}
catch
{
// your catch code
}
}
}
现在主线程被阻止,只有当你关闭它,或者你从代码中停止它时,你的程序才会停止:
Program.ServerManualResetEvent.Set();
然后它不再阻塞主线程。