diff --git a/squinnondation/squinnondation.py b/squinnondation/squinnondation.py index 1b350a4..a5135c3 100644 --- a/squinnondation/squinnondation.py +++ b/squinnondation/squinnondation.py @@ -1,5 +1,6 @@ # Copyright (C) 2020 by eichhornchen, ÿnérant # SPDX-License-Identifier: GPL-3.0-or-later + import socket from argparse import ArgumentParser from typing import Any @@ -39,14 +40,47 @@ class Squinnondation: instance = Squinnondation() instance.parse_arguments() - sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - sock.bind((instance.bind_address, instance.bind_port)) + squirrel = Squirrel(input("Enter your nickname: "), instance.bind_address, instance.bind_port) if not instance.args.bind_only: - sock.sendto(b"Hello world!", (instance.client_address, instance.client_port)) + hazelnut = Hazelnut(address=instance.client_address, port=instance.client_port) + squirrel.send_raw_data(hazelnut, b"Hello world!") - print(f"Listening on {instance.bind_address}:{instance.bind_port}...") while True: - data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes + data, addr = squirrel.receive_raw_data() print("received message: %s" % data) - sock.sendto(b"Hello squirrel!", addr) + # squirrel.send_raw_data(hazelnut, b"Hello squirrel!") + + +class Hazelnut: + """ + A hazelnut is a connected client, with its socket. + """ + def __init__(self, nickname: str = "anonymous", address: str = "localhost", port: int = 2500): + self.nickname = nickname + self.address = address + self.port = port + + +class Squirrel(Hazelnut): + """ + The squirrel is the user of the program. It can speak with other clients, that are called hazelnuts. + """ + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + self.socket.bind((self.address, self.port)) + print(f"Listening on {self.address}:{self.port}") + + def send_raw_data(self, client: Hazelnut, data: bytes) -> int: + """ + Send a raw packet to a client. + """ + return self.socket.sendto(data, (client.address, client.port)) + + def receive_raw_data(self) -> tuple[bytes, any]: + """ + Receive a packet from the socket. + TODO: Translate the address into the correct hazelnut. + """ + return self.socket.recvfrom(1024)