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);
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: