I'm trying to make a simple HTTP server with NodeMCU. I start up nodeMCU then connect it to the wifi and then run the program below. I can connect to the server from my browser. If I keep on reloading the page it would work forever, but when I stop sending requests for a minute or two, the server will somehow stop functioning. Which means, when I reload page nodeMCU does not receive any data (and cannot return any data back).
a=0
function receive(conn,payload)
a=a+1
print(payload)
local content="<!DOCTYPE html><html><head><link rel='shortcut icon' href='/'></head><body><h1>Hello!</h1><p>Since the start of the server " .. a .. " connections were made</p></body></html>"
local contentLength=string.len(content)
conn:send("HTTP/1.1 200 OK\r\nContent-Length:" .. contentLength .. "\r\n\r\n" .. content)
conn:close()
end
function connection(conn)
conn:on("receive",receive)
end
srv=net.createServer(net.TCP,1)
srv:listen(8080,connection)
Some things I did:
- I have stopped the browser from requesting favicon by adding the link to nothing.
- I set the timeout for inactive client to 1 to prevent the browser from loading for a long time (the browser keeps on loading until timeout).
- I updated my code to send some HTTP headers.
- I tried closing and opening the server after each connection (no good because if you keep on doing connections it will never stop working even without this fix).
- I added
conn:close()
as suggested by an answer here on StackOverflow.
I'm running precompiled firmware 0.9.6-dev_20150704 integer.
Edit: A solution burried in the comments below
The problem was some sort of incompatiblity between my AP and NodeMCU. To keep NodeMCU responding, I had to keep pinging it from my computer.