commit ccd9753276b6e776ae6e85ed574cab5fef065e4e Author: Pascal Engélibert Date: Sat Jan 27 17:56:24 2024 +0100 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bee8a64 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +__pycache__ diff --git a/demo.py b/demo.py new file mode 100644 index 0000000..49ebf5a --- /dev/null +++ b/demo.py @@ -0,0 +1,16 @@ +import network, sys, time + +sock = network.Sock() + +port = int(sys.argv[2]) + +if sys.argv[1] == "s": + sock.listen(("0.0.0.0", port)) + while True: + for (d, a) in sock.poll(): + print(d, a) + time.sleep(0.1) +elif sys.argv[1] == "c": + while True: + sock.send(str(time.time()), (sys.argv[3], port)) + time.sleep(1) diff --git a/network.py b/network.py new file mode 100644 index 0000000..7ae6164 --- /dev/null +++ b/network.py @@ -0,0 +1,38 @@ +import socket +from threading import Thread, Lock + +class Sock: + def __init__(self): + self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + self.queue = [] + self.queue_lock = Lock() + self.sock_thread = None + + def send(self, message, address): + self.sock.sendto(message, address) + + def listen(self, address, length=65535): + self.sock_thread = SockThread(self, address, length) + self.sock_thread.start() + + def poll(self): + if len(self.queue_lock) == 0: + return [] + with self.queue_lock: + queue = self.queue + self.queue = [] + return queue + +class SockThread(Thread): + def __init__(self, sock, address, length): + super.__init__(super) + self.sock = sock + self.sock.sock.bind(address) + self.length = self.length + self.sock.sock.bind(address) + + def run(self): + while True: + r = self.sock.sock.recv(self.length) + with self.sock.queue_lock: + self.sock.queue.append(r)