套接字接受和接收之间的竞争

Ctx*_*Ctx 6 lua nodemcu esp8266

我使用nodemcu与esp-32,最近遇到了一个恼人的问题.我从NodeMCU Github页面引用这个示例:

-- a simple HTTP server
srv = net.createServer(net.TCP)
srv:listen(80, function(conn)
    conn:on("receive", function(sck, payload)
        print(payload)
        sck:send("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n<h1> Hello, NodeMCU.</h1>")
    end)
    conn:on("sent", function(sck) sck:close() end)
end)
Run Code Online (Sandbox Code Playgroud)

这似乎并不适用于所有情况.如果我用telnet试试,没有问题:

$ telnet 172.17.10.59 80
Trying 172.17.10.59...
Connected to 172.17.10.59.
Escape character is '^]'.
GET / HTTP/1.1
HTTP/1.0 200 OK
Content-Type: text/html

<h1> Hello, NodeMCU.</h1>
Connection closed by foreign host.
Run Code Online (Sandbox Code Playgroud)

但是当使用wget时,它大部分时间都会挂起:

$ wget http://172.17.10.59/
--2017-05-12 15:00:09--  http://172.17.10.59/
Connecting to 172.17.10.59:80... connected.
HTTP request sent, awaiting response... 
Run Code Online (Sandbox Code Playgroud)

经过一些研究,根本原因似乎是,在从客户端收到第一个数据之后注册了接收回调.使用telnet手动测试时不会发生这种情况,但是对于像wget或浏览器这样的客户端,连接和接收第一个数据之间的延迟似乎太小而无法首先注册接收处理程序.

我已经查看了nodemcu代码,似乎没有一种简单的方法来解决这个问题.或者我在这里想念一些东西?

小智 0

在 HTTP/1.0 中,当存在消息正文时,您需要在 HTTP 标头中添加“Content-Length”。

例如:

"HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nContent-Length: 25 \r\n\r\n<h1> Hello, NodeMCU.</h1>"
Run Code Online (Sandbox Code Playgroud)

参考: https: //www.w3.org/Protocols/HTTP/1.0/spec.html#Content-Length