在ESP8266 Lua中向GET请求到服务器页面后清空有效负载

时间:2017-05-04 16:45:25

标签: tcp lua wifi esp8266 nodemcu

我尝试使用Lua使用ESP8266 WiFi模块从页面获取数据时获得零负载。

这是我的伪代码:

wifi.setmode(wifi.STATION)
wifi.sta.config("SSID","password")
wifi.sta.connect()

tmr.alarm(1,10000, 1, function()
    if (wifi.sta.getip() == nil) then
        print("IP unavaiable, Waiting...")
    else
        foo()
    end
end)


function foo()
    print("Inside foo function"..node.heap());
        conn = nil
        conn=net.createConnection(net.TCP,0)        -- 30 seconds timeout time of server
        conn:on("receive", function(conn, payload)
            -- local buf = "";
            startRead = false
            gpioData = ""
            print("payload : "..#payload);
            for i = 1, #payload do
                print(i); 
            end     
        end)
        conn:connect(80,"server.co.in")
        conn:on("connection", function(conn, payload)
            print("Server Connected, sending event")
            conn:send("GET /mypage?id=deadbeef HTTP/1.1 200 OK\r\nHost: server.co.in\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n") end)

        conn:on("sent",function(conn)
                print("Closing server connection")
                conn:close()
            end)
end

我正在使用NodeMCU Lua,即使我使用Arduino框架,猜测也会一样。

NodeMCU custom build by frightanic.com
    branch: master
    commit: 22e1adc4b06c931797539b986c85e229e5942a5f
    SSL: false
    modules: adc,bit,cjson,file,gpio,http,i2c,mdns,mqtt,net,node,ow,struct,tmr,uart,websocket,wifi
 build  built on: 2017-05-03 11:24
 powered by Lua 5.1.4 on SDK 2.0.0(656edbf)

我能够在服务器上看到所有请求,这意味着服务器请求代码没问题,但有效负载/响应是空白的。

输出完整空白......

请帮忙。

1 个答案:

答案 0 :(得分:2)

<div style="text-align: center;float:left"

这不是有效的HTTP请求。它看起来更像是HTTP请求和HTTP响应的混合。服务器可能只是关闭连接,因为它不理解这一点。有效的HTTP请求如下所示:

       conn:send("GET /mypage?id=deadbeef HTTP/1.1 200 OK\r\nHost: server.co.in\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n") end)

除了你正在使用HTTP / 1.1,甚至明确设置你想要使用HTTP持久连接(GET /mypage?id=deadbeef HTTP/1.1\r\n Host: ...\r\n \r\n ),尽管这种行为无论如何都隐含在HTTP / 1.1中。因此,您不能指望响应会立即像您当前那样关闭连接。此外,由于HTTP / 1.1,您需要处理HTTP分块编码。

避免这种复杂性的最简单方法是使用HTTP / 1.0而不是使用Connection: keep-alive标头或将其明确设置为Connection。如果你真的想要处理复杂性,请仔细研究the standard