2016-05-26 51 views
0

我已經制作了基於NodeMCU的小型服務器。所有的作品都很好,當我從瀏覽器連接時,但問題開始,當我嘗試從Android應用程序uisng OkHttp或Volley連接時,我收到了異常。 java.io.IOException:使用OkHttp的Connection上流的意外結束, 使用Volley的EOFException。當從Android應用發送GET請求時,NodeMCU服務器響應不良

問題是非常相似的這 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); 
     } 
    }); 

回答

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和換行符是強制性
  • 每個功能需要使用它自己傳遞的Socket實例的副本,請我如何在這兩個回調函數改名connsck,看到https://stackoverflow.com/a/37379426/131929的細節

要獲得更完整的發送示例,請看net.socket:send() in the docs。一旦你開始發送超過幾個字節,這就變得相關了。

+0

非常感謝Marcel! – stas95

+0

謝謝!我錯過了標題部分,導致了這個問題。 – satyadeepk

相關問題