我想将NodeMCU套接字客户端连接到node.js套接字服务器。 我在NodeMCU中使用Lua编程语言。我为客户端尝试了这个代码,但它没有用。
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")
node.js服务器代码经过测试并运行良好。
var app = require('http').createServer();
var io = require('socket.io')(app);
io.on('connection', function(socket){
console.log('someone is connected');
});
app.listen(3000);
答案 0 :(得分:0)
你错了NodeMCU fundamentals。 NodeMCU是异步和事件驱动的,即大多数调用都是非阻塞的。
这意味着在您发出wifi.sta.connect()
(没有阻止)后,您需要等到设备获得IP才能继续。这是缩写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)