ESP8266 send and receive sockets

Alex Pantyukhin picture Alex Pantyukhin · Nov 19, 2015 · Viewed 8.4k times · Source

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()

Answer

seblucas picture seblucas · Nov 19, 2015

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)