Clients are managed in classes

Signed-off-by: Yohann D'ANELLO <ynerant@crans.org>
This commit is contained in:
Yohann D'ANELLO 2020-12-21 16:03:55 +01:00
parent 0cf25ffbe7
commit 169625f20c
Signed by: ynerant
GPG Key ID: 3A75C55819C8CF85
1 changed files with 40 additions and 6 deletions

View File

@ -1,5 +1,6 @@
# Copyright (C) 2020 by eichhornchen, ÿnérant # Copyright (C) 2020 by eichhornchen, ÿnérant
# SPDX-License-Identifier: GPL-3.0-or-later # SPDX-License-Identifier: GPL-3.0-or-later
import socket import socket
from argparse import ArgumentParser from argparse import ArgumentParser
from typing import Any from typing import Any
@ -39,14 +40,47 @@ class Squinnondation:
instance = Squinnondation() instance = Squinnondation()
instance.parse_arguments() instance.parse_arguments()
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) squirrel = Squirrel(input("Enter your nickname: "), instance.bind_address, instance.bind_port)
sock.bind((instance.bind_address, instance.bind_port))
if not instance.args.bind_only: 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: while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes data, addr = squirrel.receive_raw_data()
print("received message: %s" % 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)