ESP8266学习之路 十 (UDP服务器通信)

一.  UDP服务器

此模式只比客户端模式下多了个 监听函数 获取客户端的信息 其余和客户端模式一样
只有客户端给服务器发送数据时才会建立通信通道连接

1.  单连接

udpserver.lua文件:

ConnectIP = ""			 --客户端连接时获取客户端的ip
ConnectPort = 0          --客户端连接时获取客户端的端口
ListenPort = 8080		 --服务器监听端口 ,也是服务器接收数据的端口

wifi.setmode(wifi.STATIONAP)

apcfg={}
apcfg.ssid="ESP8266WIFI"
apcfg.pwd="12345678"
wifi.ap.config(apcfg) 

stacfg={}
stacfg.ssid="TP-Link"
stacfg.pwd="12345678"
wifi.sta.config(stacfg)
wifi.sta.autoconnect(1)
 
UdpSocket = net.createUDPSocket()
UdpSocket:listen(ListenPort) --服务器监听端口,接收数据端口

UdpSocket:on("receive", function(socket, data, port, ip)
         print("\r\nport:"..port.."---ip:"..ip.."\r\n") 
         ConnectPort = port		--获取客户端的端口
         ConnectIP = ip			--获取客户端的ip
        uart.write(0,data) 
end)

uart.on("data",0,function(data) 
    if UdpSocket~=nil then		--只有有客户端连接时才会发送数据
        if ConnectPort~=0 then --判断是否有客户端连接的端口
            UdpSocket:send(ConnectPort, ConnectIP, data)
        end
    end
end,0)

当UDP服务器给客户端发消息时也是只发送给一个客户端

2.多连接

wifi.setmode(wifi.STATIONAP)

cfg={}
cfg.ssid="ESP8266WIFI"
cfg.pwd="12345678"
wifi.ap.config(cfg)

apcfg={}
apcfg.ssid="TP-Link"
apcfg.pwd="12345678"
wifi.sta.config(apcfg)
wifi.sta.autoconnect(1)

ConnectIP = "192.168.4.2"   --默认通信ip
ConnectPort = 8080				--默认通信端口

UdpSocket = net.createUDPSocket()   
UdpSocket:listen(ConnectPort)   --监听端口

UdpSocketTable={}   --存放UDP连接的socket
UdpIPTable={}		--存放UDP连接的ip
UdpPortTable={}		--存放UDP连接的端口
UdpConnectCnt = 0	--连接的个数
UdpCanConnect = 0	--新连接和默认连接

UdpSocket:on("receive", function(socket, data, port, ip)
    UdpCanConnect = 1
    for i=0,2 do
        if  UdpIPTable[i] == ip and UdpPortTable[i] == port  then
            UdpCanConnect = 0
        end
    end

    if  ip == ConnectIP and port == ConnectPort  then
        UdpCanConnect = 0
    end

    if  UdpCanConnect == 1 then --存放新连接的客户端
        UdpSocketTable[UdpConnectCnt] = socket
        UdpIPTable[UdpConnectCnt] = ip 
        UdpPortTable[UdpConnectCnt] = port
        print("\r\n"..UdpConnectCnt.."-Connect")
        UdpConnectCnt = UdpConnectCnt + 1
    end
    
    if  UdpConnectCnt == 3 then
        UdpConnectCnt = 0
    end
    uart.write(0,data)
end)

uart.on("data",0,function(data) 
    if  UdpSocket ~= nil then --默认连接的客户端
        UdpSocket:send(ConnectPort,ConnectIP,data)
    end
    
    for i=0,2 do	--新连接的客户端
        if  UdpSocketTable[i] ~= nil then
            UdpSocketTable[i]:send(UdpPortTable[i],UdpIPTable[i],data) 
        end
    end
        
end, 0)

UDP服务器发送消息时 连接的客户端都可以接收到数据

猜你喜欢

转载自blog.csdn.net/dianzishi123/article/details/82685996