This repository has been archived by the owner on Aug 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sender.py
58 lines (46 loc) · 1.61 KB
/
sender.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import socket
import struct
from client import Client, ClientLobby, ClientPipe
BUFFER_SIZE = 4096
class Sender:
address: str #full client address
client: Client
sock: socket
def __init__(self, client_socket: socket) -> None:
self.client = None
self.sock = client_socket
pass
def isLobby(self) -> bool:
return isinstance(self.client, ClientLobby)
def isPipe(self) -> bool:
return isinstance(self.client, ClientPipe)
def receive_all(self, n):
# Helper function to recv n bytes or return None if EOF is hit
data = bytearray()
while len(data) < n:
packet = self.sock.recv(n - len(data))
if not packet:
return None
data.extend(packet)
return data
def receive_pack(self):
# Read message length and unpack it into an integer
raw_msglen = self.receive_all(4)
if not raw_msglen:
return None
msglen = struct.unpack('<I', raw_msglen)[0]
# Read the message data
return self.receive_all(msglen)
def receive_data(self):
if self.isPipe() and self.client.auth:
return self.sock.recv(BUFFER_SIZE)
return self.receive_pack()
def handshake(self, data):
if not self.client:
msg = str(data)
exchangeMessageFlag = False #flag to identify if message exchange was started
if msg.find("Aiya!") != -1:
self.client = ClientPipe()
else:
self.client = ClientLobby()
self.client.handshake(data)