从 Android 应用程序发送 GET 请求时,NodeMCU 服务器响应错误

NodeMCU server bad response, when sending GET request from Android app

我做了一个基于NodeMCU 的小服务器。一切正常,当我从浏览器连接时,但问题开始了,当我尝试从 Android app 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);
        }
    });

您发回的不是 HTTP。它只不过是 protocol-agnostic 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 headers、HTTP/1.0 200 OK 并且换行符是必需的
  • 每个函数都需要使用它自己的传递套接字实例的副本,看看我如何在两个回调函数中将 conn 重命名为 sck,详情请参阅 https://whosebug.com/a/37379426/131929

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