- Fri Jan 09, 2015 7:08 am
#6788
ChrixXenon,
ChrixXenon wrote:lightbulb wrote:Hi ChrixXenon,
Thanks lightbulb, but I'm not getting them confused. All of the lines I quoted all come from the simple HTTP client example on the NodeMCU website.
.
Your original request only had snippets of code, but your latter post showed what you really wanted to do...."get data from a remote server"
Your getpage() function is perhaps a little wrong.
You don't need to poll like that as the socket services are largely event driven, however the "order" in which you define/execute code within nodemcu IS important.
nodemcu is an interpreter, not a "compiler", and so it pretty much executes code as codeblocks are read in (dofile is little different).
simple rule: define all your event listeners before you execute code that uses them.
In your case, its the connect that kicks everything off, so you want your listeners defined before its used.
"receive" may be called many times for a single "page", so the page has not been technically "retrieved" after the first call, you'll likely truncate data doing it the way you have.
Finally, HTTP is a complex beast at heart, and the servers to which you want to talk may want to adhere to standards more than others, so check the type and order of the headers you need to send, coupled with the protocol version you want to use.
Here is a simple GET using HTTP 1.0. I dont have a module available where i am here at work, so this was done from memory, using my good friend wget. So it "may" not work off the bat.
Note: Many HTTP servers will NOT reply to an IP without a Host: header, as the IP to which you connect may be a proxy/firewall that simply send the request on, but those environments are simply too complex to discuss here.
Code: Select allconn=net.createConnection(net.TCP, 0)
conn:on("receive", function(conn, payload)
print(payload)
end)
conn:on("disconnection", function(conn,payload)
print("disconnect")
conn:close()
end)
conn:on("connection", function(conn,payload)
print("sending...")
conn:send("HEAD / HTTP/1.0\r\n")
conn:send("Accept: */*\r\n")
conn:send("User-Agent: Mozilla/4.0 (compatible; ESP8266;)\r\n")
conn:send("\r\n")
end)
conn:dns('google.com',function(conn,ip) ipaddr=ip;
--print(ipaddr)
conn:connect(80,ipaddr)
end)