用nodemcu搭建服務器,
用lua調試(使用esplorer軟件)
官方都會提供簡單的例子
-- Start a simple http server
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
conn:on("receive",function(conn,payload)
print(payload)
conn:send("<h1> Hello, NodeMCU!!! </h1>")
end)
conn:on("sent",function(conn) conn:close() end)
end)
建立完wifi後,wifi.sta.getip() 得到ip地址 192.168.1.104
訪問 http://192.168.1.104/ 後出現錯誤提示
Bad response. The server or forwarder response doesn't look like HTTP.
分析可能是缺少和http相關的東西。
後找到其他類似程序,一個溫度溼度的應用程序
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
conn:on("receive",function(conn,payload)
local html = string.format("HTTP/1.0 200 OK\r\n"
.."Content-Type: text/html\r\n"
.."Connection: Close\r\n\r\n"
.."<h1> Hello, NodeMCU!!! </h1>")
conn:send(html,function(sent)
conn:close()
end)
end)
end)
對比發現,前段程序缺少http的定義,所以訪問 http://192.168.1.104/ 就不能以http方式訪問。
簡單修改後
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
conn:on("receive",function(conn,payload)
print(payload)
local html = string.format("HTTP/1.0 200 OK\r\n"
.."Content-Type: text/html\r\n"
.."Connection: Close\r\n\r\n"
.."<h1> Hello, NodeMCU!!! </h1>")
conn:send(html)
end)
conn:on("sent",function(conn) conn:close() end)
end)
結果:
<h1> Hello, NodeMCU!!! </h1>