Send packets rather than send raw byte array data

Signed-off-by: Yohann D'ANELLO <ynerant@crans.org>
This commit is contained in:
Yohann D'ANELLO 2020-12-21 16:03:56 +01:00
parent acf1cffec1
commit 1caf06bf24
Signed by: ynerant
GPG Key ID: 3A75C55819C8CF85
1 changed files with 26 additions and 7 deletions

View File

@ -44,14 +44,18 @@ class Squinnondation:
if not instance.args.bind_only: if not instance.args.bind_only:
hazelnut = Hazelnut(address=instance.client_address, port=instance.client_port) hazelnut = Hazelnut(address=instance.client_address, port=instance.client_port)
squirrel.send_raw_data(hazelnut, b"Hello world!") pkt = Packet()
pkt.magic = 95
pkt.version = 0
pkt.body = TLV()
msg = f"Hello world, my name is {squirrel.nickname}!"
pkt.body.raw_data = msg.encode("UTF-8")
pkt.body_length = len(pkt.body.raw_data)
squirrel.send_packet(hazelnut, pkt)
while True: while True:
data, addr = squirrel.receive_raw_data() pkt, addr = squirrel.receive_packet()
pkt = Packet.unmarshal(data) print(f"received message: {pkt.body.raw_data.decode('UTF-8')}")
print("received message: %d %d %d %s" % (pkt.magic, pkt.version, pkt.body_length, pkt.body.raw_data))
print(str(pkt.marshal()))
# squirrel.send_raw_data(hazelnut, b"Hello squirrel!")
class TLV: class TLV:
@ -115,7 +119,8 @@ class Packet:
""" """
Compute the byte array data associated to the packet. Compute the byte array data associated to the packet.
""" """
data = bytes([self.magic, self.version]) data = self.magic.to_bytes(1, "big")
data += self.version.to_bytes(1, "big")
data += self.body_length.to_bytes(2, "big") data += self.body_length.to_bytes(2, "big")
data += self.body.raw_data data += self.body.raw_data
return data return data
@ -141,12 +146,26 @@ class Squirrel(Hazelnut):
self.socket.bind((self.address, self.port)) self.socket.bind((self.address, self.port))
print(f"Listening on {self.address}:{self.port}") print(f"Listening on {self.address}:{self.port}")
def send_packet(self, client: Hazelnut, pkt: Packet) -> int:
"""
Send a formatted packet to a client.
"""
return self.send_raw_data(client, pkt.marshal())
def send_raw_data(self, client: Hazelnut, data: bytes) -> int: def send_raw_data(self, client: Hazelnut, data: bytes) -> int:
""" """
Send a raw packet to a client. Send a raw packet to a client.
""" """
return self.socket.sendto(data, (client.address, client.port)) return self.socket.sendto(data, (client.address, client.port))
def receive_packet(self) -> Tuple[Packet, Any]:
"""
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
def receive_raw_data(self) -> Tuple[bytes, Any]: def receive_raw_data(self) -> Tuple[bytes, Any]:
""" """
Receive a packet from the socket. Receive a packet from the socket.