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



我正在使用带有esp-32的nodemcu,最近遇到了一个烦人的问题。我从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 OKrnContent-Type: text/htmlrnrn<h1> Hello, NodeMCU.</h1>")
    end)
    conn:on("sent", function(sck) sck:close() end)
end)

这似乎并非在所有情况下都有效。如果我尝试使用 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.

但是在使用 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... 

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

我已经研究了nodemcu代码,似乎没有一种简单的方法来解决此问题。还是我在这里错过了什么?

在 HTTP/1.0 中,当有消息正文时,您需要在 HTTP 标头中使用"内容长度"。

例如:

"HTTP/1.0 200 OKrnContent-Type: text/htmlrnContent-Length: 25 rnrn<h1> Hello, NodeMCU.</h1>"

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