【问题标题】:NodeMCU server bad response, when sending GET request from Android app从 Android 应用程序发送 GET 请求时,NodeMCU 服务器响应错误
【发布时间】:2016-05-26 23:31:18
【问题描述】:

我已经制作了基于 NodeMCU 的小型服务器。一切正常,当我从浏览器连接时,但问题开始了,当我尝试从 Android 应用程序 uisng OkHttp 或 Volley 连接时,我收到异常。 java.io.IOException:使用 OkHttp 的连接上的流意外结束, 使用 Volley 的 EOFException。

问题与此非常相似 EOFException after server responds,但没有找到答案。

ESP 服务器代码

srv:listen(80, function(conn)

  conn:on("receive", function(conn,payload)
    print(payload)
    conn:send("<h1> Hello, NodeMCU.</h1>")
  end)
  conn:on("sent", function(conn) conn:close() end)
end)

Android 代码

final RequestQueue queue = Volley.newRequestQueue(this);
final String url = "http://10.42.0.17:80";

final StringRequest request = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    mTemperatureTextView.setText(response.substring(0, 20));
                    System.out.println(response);
                }
            },

            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    System.out.println("Error + " + error.toString());
                    mTemperatureTextView.setText("That didn't work!");
                }
            }
    );

mUpdateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            queue.add(request);
        }
    });

【问题讨论】:

    标签: android lua android-volley okhttp esp8266


    【解决方案1】:

    您发回的不是 HTTP。它只不过是一个与协议无关的 HTML 片段。此外,还存在内存泄漏问题。

    试试这个:

    srv:listen(80, function(conn)
    
      conn:on("receive", function(sck,payload)
        print(payload)
        sck:send("HTTP/1.0 200 OK\r\nServer: NodeMCU on ESP8266\r\nContent-Type: text/html\r\n\r\n<h1> Hello, NodeMCU.</h1>")
      end)
      conn:on("sent", function(sck) sck:close() end)
    end)
    
    • 您需要发回一些 HTTP 标头,HTTP/1.0 200 OK 并且换行符是强制性的
    • 每个函数都需要使用自己传递的套接字实例的副本,请参阅我如何在两个回调函数中将conn 重命名为sck,详情请参阅https://stackoverflow.com/a/37379426/131929

    有关更完整的发送示例,请查看net.socket:send() in the docs。一旦您开始发送的不仅仅是几个字节,这就会变得相关。

    【讨论】:

    • 非常感谢你,马塞尔!
    • 谢谢!我错过了标题部分,这导致了问题。
    猜你喜欢
    • 1970-01-01
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 2014-01-13
    相关资源
    最近更新 更多