【问题标题】:HTTP listener in Mono does not read HTTP requestMono 中的 HTTP 侦听器不读取 HTTP 请求
【发布时间】:2018-01-29 15:42:46
【问题描述】:

我用 C#/Mono 编写了一个在 Raspberry Pi 上运行的 HTTP 侦听器应用程序。如果我从我的 PC 使用 Postman 发送 HTTP 请求,请求不会到达 Raspberry Pi 或侦听器不会读取它。换句话说,ShowRequestData() 中的断点永远不会被命中。

但是,如果我在我的 PC 上运行该应用程序(使用 Mono 或 NET 调试器),它就可以工作。我的代码:

httpListenerWorker.DoWork += HttpListenerWorker_DoWork;
        httpListener.Prefixes.Add("http://localhost:8080/");
        try
        {
            httpListener.Start();
            httpListenerWorker.RunWorkerAsync();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Could not start HTTP listener");
        } 

private static void HttpListenerWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        while (true)
        {
            httpContext = httpListener.GetContext();
            httpRequestString = HTTP.ShowRequestData(httpContext.Request);
            if (httpRequestString != "")
            {
                messageReceived = true;
                threadWaitHandle.Set();
            }
        }
    }
public static string ShowRequestData(HttpListenerRequest request)
    {
        if (!request.HasEntityBody)
        {
            return "";
        }
        Stream body = request.InputStream;
        Encoding encoding = request.ContentEncoding;
        StreamReader reader = new StreamReader(body, encoding);

        string s = "";
        s = reader.ReadToEnd();
        body.Close();
        reader.Close();

        return s;
    }

我尝试使用 iptables 开启 8080 端口,但没有成功:

iptables -A INPUT -p tcp --dport 8080 --jump ACCEPT
iptables -A OUTPUT -p tcp --dport 8080 --jump ACCEPT
iptables-save

是不是代码有问题?我需要在 Raspberry Pi 上进行配置吗?

【问题讨论】:

  • 我怀疑您是否需要在端口 8080 上输出......但是您在 iptables 日志中看到了什么?
  • @BugFinder 我将不胜感激。我试过这个 tecadmin.net/enable-logging-in-iptables-on-linux/# ,打开日志时,我看到不断更新的消息流。

标签: c# linux http mono listener


【解决方案1】:

我发现了问题所在。看来我必须写下树莓派的确切 IP:

httpListener.Prefixes.Add("http://" + Helpers.GetLocalIP() + ":8080/");

【讨论】:

  • 你要求它只在 127.0.0.1 上收听,所以它做到了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-14
  • 2012-03-01
  • 2012-08-02
  • 1970-01-01
  • 1970-01-01
  • 2015-08-01
相关资源
最近更新 更多