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

时间:2016-05-26 23:31:18

标签: android lua android-volley okhttp esp8266

I've made little server based on NodeMCU. All works good, when I'm conneting from browser, but problem starts, when I'm trying to connect from Android app uisng OkHttp or Volley, I'm receiving exceptions. java.io.IOException: unexpected end of stream on Connection using OkHttp, EOFException using Volley.

Problem is very similar for this 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);
        }
    });

1 个答案:

答案 0 :(得分:2)

您发回的内容不是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。一旦你开始发送超过几个字节,这就变得相关了。