2024-02-10 12:30:58 +00:00
|
|
|
import socket, os, sys
|
2024-01-27 16:56:24 +00:00
|
|
|
from threading import Thread, Lock
|
|
|
|
|
2024-02-10 12:30:58 +00:00
|
|
|
NETTRACE = str(os.environ.get("NETTRACE", "0")) == "1"
|
|
|
|
|
2024-01-27 16:56:24 +00:00
|
|
|
class Sock:
|
|
|
|
def __init__(self):
|
|
|
|
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
2024-02-03 17:57:23 +00:00
|
|
|
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
|
|
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
2024-01-27 16:56:24 +00:00
|
|
|
self.queue = []
|
|
|
|
self.queue_lock = Lock()
|
|
|
|
self.sock_thread = None
|
|
|
|
|
|
|
|
def send(self, message, address):
|
2024-02-03 15:58:24 +00:00
|
|
|
if type(message) == str:
|
|
|
|
message = message.encode()
|
2024-02-10 12:30:58 +00:00
|
|
|
if NETTRACE:
|
|
|
|
print("Send to", tuple(address), ":", message, file=sys.stderr)
|
|
|
|
self.sock.sendto(message, tuple(address))
|
2024-01-27 16:56:24 +00:00
|
|
|
|
|
|
|
def listen(self, address, length=65535):
|
2024-02-10 12:30:58 +00:00
|
|
|
self.sock_thread = SockThread(self, tuple(address), length)
|
2024-02-10 17:06:30 +00:00
|
|
|
self.sock_thread.setDaemon(True)
|
2024-01-27 16:56:24 +00:00
|
|
|
self.sock_thread.start()
|
|
|
|
|
2024-02-03 17:57:23 +00:00
|
|
|
def get(self):
|
2024-02-03 15:58:24 +00:00
|
|
|
if len(self.queue) == 0:
|
2024-01-27 16:56:24 +00:00
|
|
|
return []
|
|
|
|
with self.queue_lock:
|
|
|
|
queue = self.queue
|
|
|
|
self.queue = []
|
|
|
|
return queue
|
|
|
|
|
|
|
|
class SockThread(Thread):
|
|
|
|
def __init__(self, sock, address, length):
|
2024-02-03 15:58:24 +00:00
|
|
|
Thread.__init__(self)
|
2024-01-27 16:56:24 +00:00
|
|
|
self.sock = sock
|
2024-02-03 15:58:24 +00:00
|
|
|
self.length = length
|
2024-02-10 12:30:58 +00:00
|
|
|
self.sock.sock.bind(tuple(address))
|
2024-01-27 16:56:24 +00:00
|
|
|
|
|
|
|
def run(self):
|
|
|
|
while True:
|
2024-02-03 15:58:24 +00:00
|
|
|
r = self.sock.sock.recvfrom(self.length)
|
2024-02-10 12:30:58 +00:00
|
|
|
if NETTRACE:
|
|
|
|
print("Rec from", r[1], ":", r[0], file=sys.stderr)
|
2024-01-27 16:56:24 +00:00
|
|
|
with self.sock.queue_lock:
|
|
|
|
self.sock.queue.append(r)
|