diff --git a/wiistream/networking.py b/wiistream/networking.py new file mode 100644 index 0000000..bedf58d --- /dev/null +++ b/wiistream/networking.py @@ -0,0 +1,28 @@ +import socket + + +class Networking: + + MAX_PACKET_SIZE = 512 + + def __init__(self, ip, port) -> None: + if port < 1 or port > 65535: + raise ValueError("Fuck off bad port number") + + # also validate ip? + + self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + self._socket.bind((ip, port)) + self._targets = [] + + def add_target(self, target): + self._targets.append(target) + + def send_buffer(self, to_send): + chunks = [ + to_send[i : i + Networking.MAX_PACKET_SIZE] + for i in range(0, len(to_send), Networking.MAX_PACKET_SIZE) + ] + for chunk in chunks: + for target in self._targets: + self._socket.sendto(chunk, target) diff --git a/wiistream/server.py b/wiistream/server.py index efdf148..b9b3f27 100644 --- a/wiistream/server.py +++ b/wiistream/server.py @@ -5,6 +5,7 @@ import argparse from wiistream.pong.pong import Pong +from wiistream.networking import Networking SIZE_X = 640 SIZE_Y = 480 @@ -43,7 +44,7 @@ def setup_pygame(): return screen, clock -def run_loop(screen, clock): +def run_loop(screen, clock, network): """ :return: @@ -64,16 +65,24 @@ def run_loop(screen, clock): # wait! clock.tick(60) - print(pygame.image.tostring(screen, "RGB")) + network.send_buffer(pygame.image.tostring(screen, "RGB")) def main(): args = parse_args() setup_logging(args.debug) # setup networking + try: + network = Networking("127.0.0.1", 6969) + except (ValueError, OSError) as e: + logging.error(f"Error setting up networking: {e}") + exit(-1) + + network.add_target(("127.0.0.1", 420)) + screen, clock = setup_pygame() try: - run_loop(screen, clock) + run_loop(screen, clock, network) except (KeyboardInterrupt, SystemExit): logging.info("Stopping...") except Exception as e: