Search code examples
tcpluabroadcastesp8266nodemcu

NodeMCU broadcast to all clients


I want to broadcast a request to all client that are connected to my esp8266 12f access-point

I used this to create a connection per client, means if there're 3 clients it will create 3 connections.

for mac,ip in pairs(wifi.ap.getclient()) do

   srv= net.createConnection(net.TCP, 0)
   srv:on("receive", function(client, b_response) srv:close() collectgarbage() end)
   srv:on("connection", function(client, b_request) client:send(request) end)
   srv:connect(80, ip)

end

I tried the broadcast ip srv:connect(80, "255.255.255.255") but nothing was sent

The Problem :-

What I used that every srv will overwrite the previous srv so I can not get a response if it was delayed, even so I can name every srv with a different name like srv_1, srv_2, srv_3 but this take too much memory.

What I want

Create only one connection ?


Solution

  • Your code is using TCP, which is inherently a single connection, point-to-point protocol. There's no such thing as a "broadcast" TCP connection. TCP simply does not work using broadcast. That's like trying to use a car as a boat.

    If you're sending a small amount of information, you might try UDP instead. The drawbacks are that UDP is unreliable - you can't be certain your message was received - and you'd need a lot more code to receive a response, if you want one, and you'd need to build a reliability mechanism (retransmit if no answer received, detect retransmissions in case the answer was dropped) if you care about that.

    I'd recommend that you check out the MQTT protocol - it's designed to make it easy to communicate with multiple clients. It's lightweight and MQTT clients run well on NodeMCU and Arduino processors. There's an MQTT client built into NodeMCU's LUA implementation.

    The downside is you'd need an MQTT broker that all of your NodeMCU's will connect to. The broker is usually run on a more capable processor (a Raspberry Pi is a good choice) or externally on the Internet (Adafruit offers a broker at https://io.adafruit.com/), although there are some implementations that run on an ESP8266.