squinnondation/squinnondation/squinnondation.py

53 lines
2.2 KiB
Python

# 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
class Squinnondation:
args: Any
bind_address: str
bind_port: int
client_address: str
client_port: int
def parse_arguments(self) -> None:
parser = ArgumentParser(description="MIRC client.")
parser.add_argument('bind_address', type=str, default="localhost",
help="Address of the client.")
parser.add_argument('bind_port', type=int, default=2500,
help="Port of the client. Must be between 1024 and 65535.")
parser.add_argument('--client_address', type=str, default="localhost",
help="Address of the first neighbour.")
parser.add_argument('--client_port', type=int, default=2500,
help="Port of the first neighbour. Must be between 1024 and 65535.")
parser.add_argument('--bind-only', '-b', action='store_true',
help="Don't connect to another client, only listen to connections.")
self.args = parser.parse_args()
if not (1024 <= self.args.bind_port <= 65535) and (1024 <= self.args.client_port <= 65535):
raise ValueError("Ports must be between 1024 and 65535.")
self.bind_address = self.args.bind_address
self.bind_port = self.args.bind_port
self.client_address = self.args.client_address
self.client_port = self.args.client_port
@staticmethod
def main() -> None: # pragma: no cover
instance = Squinnondation()
instance.parse_arguments()
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((instance.bind_address, instance.bind_port))
if not instance.args.bind_only:
sock.sendto(b"Hello world!", (instance.client_address, instance.client_port))
print(f"Listening on {instance.bind_address}:{instance.bind_port}...")
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print("received message: %s" % data)
sock.sendto(b"Hello squirrel!", addr)