首页 文章

NodeMCU webserver首次发送后关闭连接?

提问于
浏览
1

我在ESP-12上运行了一个带有nodemcu固件的小型Web服务器:

sv=net.createServer(net.TCP,10)

sv:listen(80,function(c)

    c:on("receive", function(c, pl)

        if(string.find(pl,"GET / ")) then
            print("Asking for index")
            c:send("Line 1")
            c:send("Line 2")
            c:send("Line 3")
            c:close()
        end

    end)
  c:on("sent",function(conn) 
    print("sended something...")
  end)
end)

看来我的连接在第一次发送后关闭,在我的浏览器中我只看到“第1行”文本,第2行a 3没有出现,在我的串口控制台中,我只是看到“发送的东西”文本一次,甚至评论close语句并让连接超时不会改变行为 . 我在这里想念的是什么?

2 回答

  • 1

    我不认为你可以多次使用 send . 每当我使用我的ESP8266作为服务器时,我使用缓冲变量:

    sv=net.createServer(net.TCP,10)
    -- 'c' -> connection, 'pl' -> payload
    sv:listen(80,function(c)
    
        c:on("receive", function(c, pl)
    
            if(string.find(pl,"GET / ")) then
                print("Asking for index")
                local buffer = ""
                buffer = buffer.."Line 1"
                buffer = buffer.."Line 2"
                buffer = buffer.."Line 3"
                c:send(buffer)
                c:close()
            end
    
        end)
        c:on("sent",function(c)
            print("sended something...")
        end)
    end)
    

    编辑:再次读取文档后,send可以使用另一个带回调函数的参数,它可以用于具有多个发送命令 . 从来没有试过它:( .

    编辑2:如果你有一个很长的字符串要发送,最好使用table.concat

  • 1

    net.socket:send()文档提供了一个很好的例子,我在这里重复一遍 .

    srv = net.createServer(net.TCP)
    
    function receiver(sck, data)
      local response = {}
    
      -- if you're sending back HTML over HTTP you'll want something like this instead
      -- local response = {"HTTP/1.0 200 OK\r\nServer: NodeMCU on ESP8266\r\nContent-Type: text/html\r\n\r\n"}
    
      response[#response + 1] = "lots of data"
      response[#response + 1] = "even more data"
      response[#response + 1] = "e.g. content read from a file"
    
      -- sends and removes the first element from the 'response' table
      local function send(localSocket)
        if #response > 0 then
          localSocket:send(table.remove(response, 1))
        else
          localSocket:close()
          response = nil
        end
      end
    
      -- triggers the send() function again once the first chunk of data was sent
      sck:on("sent", send)
    
      send(sck)
    end
    
    srv:listen(80, function(conn)
      conn:on("receive", receiver)
    end)
    

相关问题