NodeMCU socket client using Lua doesn't connect

422 views Asked by At

I want to connect a NodeMCU socket client to node.js socket server. I'm using Lua programming language in NodeMCU. I tried this code for the client but it didn't work.

wifi.setmode(wifi.STATION)
wifi.sta.config("SSID","Password")
wifi.sta.connect()
ip = wifi.sta.getip()
print("your IP is "..ip)

sk = net.createConnection(net.TCP, 0)

sk:on("receive", function ( sck,c )
  print (c)
end)

sk:on("connection", function ( sck,c )
  print("connected")
  sk:send("Helloooo...")
end)

sk:connect(3000,"192.168.1.4")

The node.js server code is tested and worked well.

var app = require('http').createServer();
var io = require('socket.io')(app);

io.on('connection', function(socket){
  console.log('someone is connected');
});

app.listen(3000);
1

There are 1 answers

0
Marcel Stör On BEST ANSWER

You got the NodeMCU fundamentals wrong. NodeMCU is asynchronous and event-driven i.e. most calls are non-blocking.

That means that after you issue wifi.sta.connect() (which doesn't block) you need to wait until the device got an IP before you can continue. Here's an abbreviated startup sequence from our docs:

function startup()
    -- do stuff here
end

print("Connecting to WiFi access point...")
wifi.setmode(wifi.STATION)
wifi.sta.config(SSID, PASSWORD)
-- wifi.sta.connect() not necessary because config() uses auto-connect=true by default
tmr.alarm(1, 1000, 1, function()
    if wifi.sta.getip() == nil then
        print("Waiting for IP address...")
    else
        tmr.stop(1)
        print("WiFi connection established, IP address: " .. wifi.sta.getip())
        print("You have 3 seconds to abort")
        print("Waiting...")
        tmr.alarm(0, 3000, 0, startup)
    end
end)