c# - 使用 SimpleHttpServer 的 C#/.NET 应用程序不向浏览器返回响应?
问题描述
注意:这不是 Python 应用程序,它是 C#。
我创建了一个 C# 应用程序,我试图使用我在网上找到的这个简单的 C# 模块将其制作成一个简单的服务器:
https://gist.github.com/aksakalli/9191056
我把所有东西都连接好了,但是当我从浏览器访问我的服务器时,它永远不会收到响应。我通过使用Chrome 调试器中的网络选项卡检查了这一点。我看到正在发出请求,但响应子面板始终为空。
我跟踪了我的服务器代码,它运行没有错误,但是在将标头添加到响应并关闭输出流之后,浏览器端没有任何反应。以下是我的代码的相关部分。谁能告诉我为什么我的浏览器从来没有看到响应以及我该如何解决这个问题?
public delegate Task<string> ProcessHttpContext(HttpListenerContext context);
private ProcessHttpContext _processHttpContextFunc = null;
public SimpleHTTPServer(string path, int port, ProcessHttpContext processHttpContextFunc)
{
this.Initialize(path, port);
this._processHttpContextFunc = processHttpContextFunc;
}
public SimpleHTTPServer(string path)
{
//get an empty port
TcpListener l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
int port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
this.Initialize(path, port);
}
public void Stop()
{
_serverThread.Abort();
_listener.Stop();
}
private void Listen()
{
_listener = new HttpListener();
_listener.Prefixes.Add("http://+:" + _port.ToString() + "/main-page/");
_listener.Start();
while (true)
{
try
{
HttpListenerContext context = _listener.GetContext();
Process(context);
}
catch (Exception ex)
{
Debug.WriteLine("Exception occurred during GetContext() call: " + ex.Message);
if (ex.InnerException != null)
Debug.WriteLine(" Inner Exception: " + ex.InnerException.Message);
}
}
}
async private void Process(HttpListenerContext context)
{
if (context == null)
throw new ArgumentNullException("The context parameter is empty.");
try
{
// Call it with the current context.
string strResult = await this._processHttpContextFunc(context);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strResult);
context.Response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
context.Response.AddHeader("Content-Length", strResult.Length.ToString());
context.Response.SendChunked = false;
context.Response.StatusCode = (int)HttpStatusCode.OK;
context.Response.StatusDescription = "OK";
context.Response.OutputStream.Write(bytes, 0, bytes.Length);
context.Response.OutputStream.Flush();
}
}
catch (Exception ex)
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
context.Response.OutputStream.Close();
}
private void Initialize(string path, int port)
{
this._rootDirectory = path;
this._port = port;
_serverThread = new Thread(this.Listen);
_serverThread.Start();
}
解决方案
推荐阅读
- pandas - 如何根据数据中的日期在数据框中添加月份列?
- java - 尝试使用 JGraphT 和 JGraphX 构建和可视化 Gomory-Hu-Tree
- javascript - 访问字符串列表以推送或更新到模型中的列表
- youtube - youtube 实时聊天节目仅在桌面上 - 在移动设备上什么都看不到
- dashboard - 在超集仪表板中定位图表的问题
- ionic-framework - 如何根据通过蓝牙从 arduino 收到的数据浏览 ionic 应用程序
- powershell - 为什么我不能在 write-host 中使用 $_?
- c# - (A) 等待类完成实例化
- angular - 如何对 Angular @Input 的 setter 和 getter 进行单元测试
- anaconda - 无法创建新的 jupyter 笔记本。POST 中缺少错误“_xsrf”参数