4
votes

I'm new to NodeMCU programming for ESP8266. I need to send strings to the server and receive response strings. So I wrote some code, but it doesn't work properly. My program works through time, and then displays a message that the memory is full. Can you help me?

---------init funсtion-----------------
wifi.setmode(wifi.STATION)
wifi.sta.config("TP-LINK_ROBOT","63793246")
wifi.sta.connect()
---------------------------------------------

function hello (sck,c)
   print (c)
   sk:close()
   if c == "Thank you" then
   print("Great!")
   end 
end

function test()
sk=net.createConnection(net.TCP, 0)
sk:on("receive", hello)
sk:on("sent", function(sck)  end)
sk:connect(9999,"192.168.0.100")
sk:send("HELLO")
print("sent to server")
end

test()
1
You definitely need to read the FAQ at esp8266.com/wiki/doku.php?id=nodemcu-unofficial-faq. vlad59's answer is spot on. You need to understand tha Lua is fully asynchronous and, therefore, you need to work with callbacks.Marcel Stör
@MarcelStör Thank youAlex Pantyukhin

1 Answers

4
votes

This is the code I'm using with latest dev firmware. I tried to adapt it to your case. It should work as is.

As usual with nodemcu, you always have to remember that it's heavily event-based.

sk=net.createConnection(net.TCP, 0)
sk:on("receive", function(sck, c)
    print(c)
    if c == "Thank you" then
      print("Great!")
    end 
end )
sk:connect(9999,"192.168.0.100")
sk:on("connection", function(sck,c)
  -- Wait for connection before sending.
  sk:send("HELLO")
end)