gpt4 book ai didi

HttpListener 的 C# 问题

转载 作者:太空狗 更新时间:2023-10-29 22:24:28 28 4
gpt4 key购买 nike

我使用 HttpListener 编写了一个 Windows 服务来异步处理来自点的请求。

它工作正常,但有时会遇到问题,需要重新启动服务或服务器才能修复。最初我声明了监听器对象:

public HttpListener PointsListener = new HttpListener();

这是方法的代码,我从这里开始监听。我从服务的 OnStart 方法调用它:

    public string ListenerStart()
{
try
{
if (!PointsListener.IsListening)
{
PointsListener.Prefixes.Add(String.Concat("http://*:", points_port, "/"));
PointsListener.Start();
PointsListener.BeginGetContext(PointProcessRequest, PointsListener);

LogWriter("Http listener activated on port " + points_port);
return "Listener started";
}
else
{
return "Listener is already started!";
}

}
catch (Exception err)
{
LogWriter("Error in LIstenerStart \r\n" + err.ToString());
return ("Error: " + err.Message);
}
}

下面是处理请求的方法:

    private void PointProcessRequest(IAsyncResult result)
{
HttpListener listener = (HttpListener)result.AsyncState;
HttpListenerContext context = listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
response.KeepAlive = false;
System.IO.Stream output = response.OutputStream;

try
{
//declaring a variable for responce
string responseString = "<html>My Response: request is not allowed by server protocol</html>";


// Commands and actions to set responceString

byte[] buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
output.Write(buffer, 0, buffer.Length);
}
catch (Exception err)
{
LogWriter("Error in PointProcessRequest: \r\n" + err.ToString());
}
finally
{
try
{
output.Flush();
output.Close();
response.Close();
}
catch (Exception err)
{
LogWriter("Error in PointProcessRequest CLOSING OUTPUT STREAM: \r\n" + err.ToString());
}
finally
{
PointsListener.BeginGetContext(PointProcessRequest, PointsListener);
}
}
}

它有时运行良好,但日志中出现以下错误:

Error in PointProcessRequest: 
System.Net.HttpListenerException: The specified network name is no longer available
в System.Net.HttpResponseStream.Write(Byte[] buffer, Int32 offset, Int32 size)
в ARK_Dealer.ark.PointProcessRequest(IAsyncResult result)

[26.01.2011 9:00:54] Error in PointProcessRequest CLOSING OUTPUT STREAM:
System.InvalidOperationException: Cannot close stream until all bytes are written.
в System.Net.HttpResponseStream.Dispose(Boolean disposing)
в System.IO.Stream.Close()
в ARK_Dealer.ark.PointProcessRequest(IAsyncResult result)

我认为问题出现在某个点向服务器发送请求但在接收应答断开连接之前。

如何防止抛出异常?响应对象是否会自动妥善处理?我该如何解决这个问题?

最佳答案

我在生产中使用 HttpListener,我找到了解决这个问题的最佳方法,无需添加一大堆 try/catch block ,这些 block 对传递手头代码的逻辑没有任何作用;是非常简单地设置 Listener.IgnoreWriteExceptions = true; 并且,voilà 不再有写入异常!

关于HttpListener 的 C# 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4801868/

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