From a4cf467e599aa37eb63e2372b2afe3c24c91710b Mon Sep 17 00:00:00 2001 From: Yohann D'ANELLO Date: Mon, 21 Dec 2020 16:03:58 +0100 Subject: [PATCH] Translate tuples (address, port) into hazelnuts Signed-off-by: Yohann D'ANELLO --- squinnondation/squinnondation.py | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/squinnondation/squinnondation.py b/squinnondation/squinnondation.py index 073444d..112b7ed 100644 --- a/squinnondation/squinnondation.py +++ b/squinnondation/squinnondation.py @@ -59,8 +59,19 @@ class Squinnondation: squirrel.send_packet(hazelnut, pkt) while True: - pkt, addr = squirrel.receive_packet() - print(f"received message: {pkt.body.data.decode('UTF-8')}") + pkt, hazelnut = squirrel.receive_packet() + print(pkt.body.data.decode('UTF-8')) + pkt = Packet() + pkt.magic = 95 + pkt.version = 0 + pkt.body = DataTLV() + msg = f"Hello my dear hazelnut, I am {squirrel.nickname}!" + pkt.body.data = msg.encode("UTF-8") + pkt.body.sender_id = 42 + pkt.body.nonce = 18 + pkt.body.length = len(msg) + 1 + 1 + 8 + 4 + pkt.body_length = pkt.body.length + 2 + squirrel.send_packet(hazelnut, pkt) class TLV: @@ -343,8 +354,19 @@ class Squirrel(Hazelnut): super().__init__(*args, **kwargs) self.socket = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) self.socket.bind((str(self.address), self.port)) + self.hazelnuts = dict() print(f"Listening on {self.address}:{self.port}") + def find_hazelnut(self, address: str, port: int) -> Hazelnut: + """ + Translate an address into a hazelnut, and store it in the list of the hazelnuts, ie. the neighbours. + """ + if (address, port) in self.hazelnuts: + return self.hazelnuts[(address, port)] + hazelnut = Hazelnut(address=address, port=port) + self.hazelnuts[(address, port)] = hazelnut + return hazelnut + def send_packet(self, client: Hazelnut, pkt: Packet) -> int: """ Send a formatted packet to a client. @@ -357,17 +379,16 @@ class Squirrel(Hazelnut): """ return self.socket.sendto(data, (str(client.address), client.port)) - def receive_packet(self) -> Tuple[Packet, Any]: + def receive_packet(self) -> Tuple[Packet, Hazelnut]: """ Receive a packet from the socket and translate it into a Python object. TODO: Translate the address into the correct hazelnut. """ data, addr = self.receive_raw_data() - return Packet.unmarshal(data), addr + return Packet.unmarshal(data), self.find_hazelnut(addr[0], addr[1]) 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)