首页 > 解决方案 > 使用 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();
    }

标签: c#httplistener

解决方案


推荐阅读