c# - Mono 中的 HTTP 监听器不读取 HTTP 请求

标签 c# linux http mono listener

我用 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 上进行配置吗?

最佳答案

我已经发现问题了。看来我必须写出 Raspberry Pi 的确切 IP:

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

关于c# - Mono 中的 HTTP 监听器不读取 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48504945/

相关文章:

c++ - 使用UDP套接字发送时如何设置源地址

http - 套接字连接是否比 Blackberry 上的 http 更快?

html - 浏览器刷新行为

c# - 我如何使用 Elysium 项目?

c# - linq sum如何显示为货币

Python 脚本在 Spyder 中完美运行(在 Windows 上)——在 Linux 上不起作用

linux - 使用 mmap 访问 PCI-e 内存空间

asp.net-mvc - 使用 Http 模块 response.redirect 给出 ERR_TOO_MANY_REDIRECTS

c# - 为什么 Asp.net MVC 不能区分具有不同参数的两个 Action ?

c# - 将项目添加到自定义列表框