2015-11-21 70 views
1

我有一个小的Web服务器上我的ESP-12运行与nodemcu固件:NodeMCU网络服务器首次发送后关闭连接?

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行3没有出现,并且在我的串行控制台中,我只是一次看到“发送内容”文本,甚至评论关闭语句并让连接超时不会改变行为。我在这里错过了什么?

回答

1

我不认为你可以使用发送多次。每当我用我的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

+0

前段时间我使用了缓冲解决方案,它的工作原理是,但问题是如果你不得不缓冲一个大文件,你有可能冒Ram内存问题,也许回调工作的想法,我会尝试。谢谢 – DomingoSL

+0

确实我应该想到这一点(我曾经遇到这个问题)。我修改了我的答案,添加了一个关于table.concat的笔记 – seblucas

+0

这是因为回调函数重新使用'c'而泄漏内存。我将添加一个替代答案,请参阅http://stackoverflow.com/a/37379426/131929和http://stackoverflow.com/a/36094397/131929以了解相关问题。 –

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)