ConnectCnt = 0wifi.setmode(wifi.STATIONAP)cfg={}cfg.ssid="HiWifi8266"--模塊的WIFI信號名字cfg.pwd="11223344"--密碼wifi.ap.config(cfg)--寫入配置wifi.sta.config("qqqqq","11223344")--模塊連接的路由器名稱和密碼wifi.sta.connect()tmr.alarm(2, 3000, 1, function()--3s檢測一次是否連接上路由器 if wifi.sta.getip() ~= nil then tmr.stop(2) print("Connected, IP is "..wifi.sta.getip())--打印分得的IP endend)srv=net.createServer(net.TCP,28800)--創建TCP服務 tmr.alarm(3, 1000, 1, function()--1s進入一次看是否需要建立新的監聽 if ConnectCnt == 0 then srv:listen(8080,function(conn0) print("Connect0") ConnectCnt = 1 if connect1 ~= nil then connect1:close() end connect0 = conn0 conn0:on("receive",function(conn0,payload) print(payload) end) end) end if ConnectCnt == 1 then srv:listen(8080,function(conn1) print("Connect1") ConnectCnt = 2 if connect2 ~= nil then connect2:close() end connect1 = conn1 conn1:on("receive",function(conn1,payload) print(payload) end) end) end if ConnectCnt == 2 then srv:listen(8080,function(conn2) print("Connect2") ConnectCnt = 3 if connect3 ~= nil then connect3:close() end connect2 = conn2 conn2:on("receive",function(conn2,payload) print(payload) end) end) end if ConnectCnt == 3 then srv:listen(8080,function(conn3) print("Connect3") ConnectCnt = 0 if connect0 ~= nil then connect0:close() end connect3 = conn3 conn3:on("receive",function(conn3,payload) print(payload) end) end) endend)uart.setup(0,9600,8,0,1,0) uart.on("data", function(data) if connect0 ~= nil then connect0:send(data) end if connect1 ~= nil then connect1:send(data) end if connect2 ~= nil then connect2:send(data) end if connect3 ~= nil then connect3:send(data) end end, 0)
這次的建立服務可以連接3個客戶端,也不知道到底能連接多少個,,,沒測試,,就先寫了3個
注意看一下哈,我是這樣設置的
if ConnectCnt == 0 then srv:listen(8080,function(conn0) print("Connect0") ConnectCnt = 1 if connect1 ~= nil then connect1:close() end connect0 = conn0 conn0:on("receive",function(conn0,payload) print(payload) end) end) end
conn0連接就把conn1關掉,
conn1連接就把conn2關掉,
conn2連接就把conn3關掉,
conn03接就把conn0關掉,
所以呢現在做的最多可以3個客戶端連接,,,,改天試一試能不能做到65535個連接......看看最多能連接多少個
最后的串口發送就不用說了,,,只是在原先的基礎上先判斷了是不是 nil 然后再發送
那就測試一下
連接模塊的無線
其實也可以不用連接模塊的無線,,因為模塊連接路由器了,所以電腦或者手機連接路由器后可以連接模塊連接路由器后分得的IP來測試
就用這四個來測試,用串口助手看信息,,對了模塊默認內部IP:192.168.4.1