ESP8266 NodeMCU Lua “Socket client”和“Python Server”连接不成功

我试图将一个 NodeMCU Socket client 程序连接到一个 Python server 程序,但无法建立连接。

我测试了一个简单的 Python client server 代码,并成功运行了它。

Python Server 代码

import socket               # 导入 socket 模块

s = socket.socket()         # 创建 socket 对象
host = socket.gethostname() # 获取本地主机名
port = 12345                # 为服务定一个端口号
s.bind((host, port))        # 绑定端口

s.listen(5)                 # 现在等待客户端连接。
while True:
   c, addr = s.accept()     # 建立客户端连接。
   print 'Got connection from', addr
   print c.recv(1024)
   c.send('Thank you for connecting')
   c.close()                # 关闭连接

Python client 代码 (通过该代码,我测试了以上代码)

import socket               # 导入 socket 模块

s = socket.socket()         # 创建 socket 对象
host = socket.gethostname() # 获取本地主机名
port = 12345                # 为服务定一个端口号

s.connect((host, port))
s.send('Hi i am aslam')
print s.recv(1024)
s.close                     #关闭连接

服务器端输出如下

Got connection from ('192.168.99.1', 65385)
Hi i am aslam

NodeMCU 代码

--将 wifi 设置为 station
print("Setting up WIFI...")
wifi.setmode(wifi.STATION)
--根据你的无线路由器设置进行修改
wifi.sta.config("xxx", "xxx")
wifi.sta.connect()

function postThingSpeak()
  print("hi")
  srv = net.createConnection(net.TCP, 0)
  srv:on("receive", function(sck, c) print(c) end)
  srv:connect(12345, "192.168.0.104")
  srv:on("connection", function(sck, c)
    print("Wait for connection before sending.")
    sck:send("hi how r u")
  end)
end

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, postThingSpeak)
  end
end)

但是当我运行 NodeMCU 时,在 Python server 中没有响应。

在 ESPlorer 控制台中的输出如下

Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
WiFi connection established, IP address: 192.168.0.103
You have 3 seconds to abort
Waiting...
hi

我在做错了什么或遗漏了一些步骤吗?

感谢您的指导。

点赞
用户131929
用户131929

第二次我重新访问后,终于明白了。我第一次扫描你的 Lua 代码时可能太快了。

你需要在建立连接之前设置所有的事件处理程序(srv:on)。否则这些处理程序可能无法触发 - 这取决于连接建立的快慢。

srv = net.createConnection(net.TCP, 0)
srv:on("receive", function(sck, c) print(c) end)
srv:on("connection", function(sck)
  print("Wait for connection before sending.")
  sck:send("hi how r u")
end)
srv:connect(12345,"192.168.0.104")

我们 API 文档中的示例是错误的,但已经在 dev 分支中修复了。

2017-01-01 13:10:46