2016-12-27 7 views
0

nodeMCUソケットクライアントをnode.jsソケットサーバーに接続したいとします。 私はNodeMCUでLuaプログラミング言語を使用しています。私はクライアントのためにこのコードを試しましたが、うまくいきませんでした。Luaを使用したNodeMCUソケットクライアントは接続されません

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サーバーコードは、テストされて正常に動作します。

答えて

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) 
関連する問題