Skip to content

Instantly share code, notes, and snippets.

@cassc
Last active October 7, 2021 03:47
Show Gist options
  • Save cassc/1e3750476ba13eff06daa0943e2b3e63 to your computer and use it in GitHub Desktop.
Save cassc/1e3750476ba13eff06daa0943e2b3e63 to your computer and use it in GitHub Desktop.
Send UDP broadcast and read replies from all clients
# Send UDP broadcast and read reply
# Edited from
# https://gist.github.com/ninedraft/7c47282f8b53ac015c1e326fffb664b5
import socket
import time
import binascii
import _thread as thread
PORT = 37020
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
server.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
server.settimeout(1)
def receive():
while True:
try:
data, addr = server.recvfrom(1024)
print(f'GET {data} FROM {addr}')
except Exception:
pass
thread.start_new_thread(receive, ())
iid = 0
while True:
msg = f'{iid}'.encode()
iid += 1
print(f'SEND {msg}')
try:
server.sendto(msg, ('<broadcast>', PORT))
except Exception as e:
print(f'Ignore send error {e}')
time.sleep(1)
@cassc
Copy link
Author

cassc commented Oct 7, 2021

Clients are actually UDP server listening on the broadcasting port:

import socket
import time
import binascii

UDP_IP = "0.0.0.0"
UDP_PORT = 37020

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))


while True:
    data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
    msg = data.decode('utf8')
    # msg = binascii.hexlify(data)
    print(f"RECV {msg} FROM {addr}")
    sent = sock.sendto(msg.encode(), addr)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment