How to send multiple data (conn:send()) with the new SDK (NodeMCU)

后端 未结 2 1381
南笙
南笙 2021-01-03 10:42

I\'ve been reading the NodeMCU documentation and several closed issues about the change of SDK that previouly allowed to send multiple data streams (acting like a queued net

2条回答
  •  渐次进展
    2021-01-03 11:26

    Here is my solution without using tables, saving some memory:

    function Sendfile(sck, filename, sentCallback)
        if not file.open(filename, "r") then
            sck:close()
            return
        end
        local function sendChunk()
            local line = file.read(512)
            if line then 
                sck:send(line, sendChunk) 
            else
                file.close()
                collectgarbage()
                if sentCallback then
                    sentCallback()
                else
                    sck:close()
                end
            end
        end
        sendChunk()
    end
    
    
    srv = net.createServer(net.TCP)
    srv:listen(80, function(conn)
        conn:on("receive", function(sck, req)
            sck:send("HTTP/1.1 200 OK\r\n" ..
                "Server: NodeMCU on ESP8266\r\n" ..
                "Content-Type: text/html; charset=UTF-8\r\n\r\n", 
                function()
                    Sendfile(sck, "head.html", function() Sendfile(sck, "body.html") end)
                end)        
        end)
    end)
    

    And this is for serving single files:

    function Sendfile(client, filename)
        if file.open(filename, "r") then
            local function sendChunk()
                local line = file.read(512)
                if line then 
                    client:send(line, sendChunk) 
                else
                    file.close()
                    client:close()
                    collectgarbage()
                end
            end
            client:send("HTTP/1.1 200 OK\r\n" ..
                "Server: NodeMCU on ESP8266\r\n" ..
                "Content-Type: text/html; charset=UTF-8\r\n\r\n", sendChunk)
        else
            client:send("HTTP/1.0 404 Not Found\r\n\r\nPage not found")
            client:close()
        end
    end
    
    
    srv = net.createServer(net.TCP)
    srv:listen(80, function(conn)
        conn:on ("receive", function(client, request)
            local path = string.match(request, "GET /(.+) HTTP")
            if path == "" then path = "index.htm" end
            Sendfile(client, path)
        end)
    end)
    

提交回复
热议问题