Last active
October 7, 2021 03:47
-
-
Save cassc/1e3750476ba13eff06daa0943e2b3e63 to your computer and use it in GitHub Desktop.
Send UDP broadcast and read replies from all clients
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Clients are actually UDP server listening on the broadcasting port: