As the title says... Chat on...

User avatar
By GeoReb
#23671 Hello,

I am using NodeMCU and trying to GET a text file from my server using the code below...

Code: Select allconn=net.createConnection(net.TCP, false)
conn:on("receive", function(conn, payload) print(payload) end)
conn:connect(80,"myserver")
conn:send("GET /test.txt HTTP/1.1\r\nHost: myserver\r\n"
.."Connection: keep-alive\r\nAccept: */*\r\n\r\n")

The payload variable prints without a problem, however, I want to edit the payload variable once I've received it from the server, but nil is returned when I execute a second print...

Code: Select allprint(payload)

How can I get access to the txt file?!

Many thanks,
George
User avatar
By TerryE
#23672 function(conn, payload) print(payload) end is a callback which is invoked when a TCP record is received from the server (in response to the get). payload is a parameter and therefore local to the function. You have to process the payload within the function, as it isn't in scope elsewhere.

Read my FAQ lnk below where I explain this.
User avatar
By GeoReb
#23696 This is a great help - thankyou! I suspected as much.

Once I've processed payload in the way that I need to, I would like to make the output variable(s) available outside the function. Is this possible, as I don't want to have to contain my entire program within that function...??

Many thanks in advance,
George
User avatar
By TerryE
#23724 George, if you want to find out how to do things then you should really be prepared to read and to understand the FAQ where I've covered these points. I wrote the thing so I wouldn't have to keep repeating the same answers to the same frequent Qs.

Lua on the ESP8266 is event driven because that's how the sdk works. You typically pass context between events by using global variables, so get your payload routine to process / build up a response in a global table and then when its complete you can use a timer (with a 10mSec delay say) to kick off any follow-up processing by assessing this global table, then set it to nil when you are done to get rid of it.