-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket_handler.py
290 lines (215 loc) · 9.25 KB
/
socket_handler.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#Snaildash is a small game created in the scope of a school project
#Copyright (C) 2022 Louis HEREDERO & Mathéo BENEY
import socket
import threading
import time
class SocketHandler:
"""Class handling communication between the two devices"""
SEND_INTERVAL = 0.1 # interval in seconds between send loops
LAN = 0
WAN = 1
MSG_SEP = b"<->"
def __init__(self, manager):
"""Initializes a SocketHandler instance
Args:
manager (Manager): manager instance
"""
self.manager = manager
self.running = False
self.sock = None
self.in_thread = None
self.out_thread = None
self.connect_s = None
self.type = None
def reset(self):
"""Resets messages state"""
self._msgs = {}
self._last_recv = -1
self._latest = -1
self._msg_id = 0
self.type = None
def connect(self):
"""Connects to the match-making server and waits for opponent"""
self.reset()
self.running = True
if self.connect_s is None:
self.connect_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect_s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
config = self.manager.config["connection_server"]
self.connect_s.connect((config["url"], config["port"]))
self.connect_s.settimeout(2)
local_ip, local_port = self.connect_s.getsockname()
musername = self.manager.musername
msg = f"{local_ip}|{local_port}|{musername}"
self.local_addr = (local_ip, local_port)
self.connect_s.sendall(msg.encode("utf-8"))
self.connect_thread = threading.Thread(target=self.wait_for_opponent)
self.connect_thread.start()
def wait_for_opponent(self):
"""Waits for opponent asynchronously"""
connected = False
while self.running:
try:
data = self.connect_s.recv(2048)
except socket.timeout:
continue
else:
if data.startswith(b"ping"): continue
is_host, is_lan, pub_ip, pub_port, priv_ip, priv_port, self.manager.ousername = data.decode("utf-8").split("|", 6)
is_host, is_lan, pub_port, priv_port = bool(int(is_host)), bool(int(is_lan)), int(pub_port), int(priv_port)
self.type = self.LAN if is_lan else self.WAN
if is_host:
self.manager.init_host()
else:
self.manager.init_guest()
self.pub_addr = (pub_ip, pub_port)
self.priv_addr = (priv_ip, priv_port)
if self.type == self.WAN:
self.finalize_wan_connection()
else:
self.finalize_lan_connection()
connected = True
break
if not connected:
self.connect_s.sendall(b"cancel")
self.connect_s.close()
self.connect_s = None
def finalize_wan_connection(self):
"""Establishes the connection with the opponent (WAN)"""
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
self.sock.bind(self.local_addr)
self.sock.settimeout(0.1)
while self.running:
self.sock.sendto(b"handshake-priv|0", self.priv_addr)
self.sock.sendto(b"handshake-pub|0", self.pub_addr)
try:
data = self.sock.recv(2048)
except socket.timeout:
data = b""
if data == b"handshake-priv|1":
self.sock.connect(self.priv_addr)
self.type = self.LAN
break
elif data == b"handshake-pub|1":
self.sock.connect(self.pub_addr)
self.type = self.WAN
break
elif data == b"handshake-priv|0":
self.sock.sendto(b"handshake-priv|1", self.priv_addr)
elif data == b"handshake-pub|0":
self.sock.sendto(b"handshake-pub|1", self.pub_addr)
if self.running:
m = f"handshake-{['priv', 'pub'][self.type]}|1"
self._msgs[-1] = [m, False]
self.sock.settimeout(1)
self.in_thread = threading.Thread(target=self.listen_loop)
self.out_thread = threading.Thread(target=self.send_loop)
self.in_thread.start()
self.out_thread.start()
self.manager.on_connected()
def finalize_lan_connection(self):
"""Establishes the connection with the opponent (LAN)"""
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
self.sock.bind(self.local_addr)
if self.manager.is_host():
self.sock.listen(1)
conn, addr = self.sock.accept()
self.sock.close()
self.sock = conn
else:
self.sock.connect(self.priv_addr)
self.sock.settimeout(1)
if self.type == self.WAN:
self.in_thread = threading.Thread(target=self.listen_loop_wan)
else:
self.in_thread = threading.Thread(target=self.listen_loop_lan)
self.in_thread.start()
self.manager.on_connected()
def sock_send(self, msg):
"""Sends a message through the socket. If the socket is closed,
the message will silently be ignored
Args:
msg (str or bytes): the message to send
"""
if not self.running or self.sock is None: return
if isinstance(msg, str):
msg = msg.encode("utf-8")
msg += self.MSG_SEP
self.sock.sendall(msg)
def listen_loop_wan(self):
"""Listens for incoming messages asynchronously and responds accordingly.
This method implements TCP features over UDP
"""
while self.running:
try:
data = self.sock.recv(2048)
except:
continue
msgs = data.split(self.MSG_SEP)
for data in msgs:
if data == "": continue
if data.startswith(b"handshake"): continue
data = data.split(b"|", 2)
type_, id_ = data[:2]
id_ = int(id_.decode("utf-8"))
# Message
if type_ == b"msg":
if id_ > self._last_recv+1:
self._latest = max(self._latest, id_)
self.sock_send(f"res|{self._last_recv+1}")
elif id_ <= self._last_recv:
self.sock_send(f"ack|{id_}")
else:
self.manager.on_receive(data[2])
if id_ < self._latest:
self.sock_send(f"res|{id_+1}")
else:
self._latest = id_
self._last_recv = id_
# Acknowledge
elif type_ == b"ack":
self._msgs[id_][1] = True
# Resend
elif type_ == b"res":
self.sock_send(self._msgs[id_][0])
def listen_loop_lan(self):
"""Listens for incoming messages asynchronously over TCP."""
while self.running:
try:
data = self.sock.recv(2048)
except:
continue
msgs = data.split(self.MSG_SEP)
for data in msgs:
if data == "": continue
self.manager.on_receive(data)
def send_loop(self):
"""Sends un-acknowledged messages asynchronously every SEND_INTERVAL seconds"""
while self.running:
msgs = self._msgs.copy()
for id_, [msg, ack] in msgs.items():
if not ack:
self.sock_send(msg)
time.sleep(self.SEND_INTERVAL)
def send(self, msg):
"""Adds a msg to the send queue
Args:
msg (bytes): data to send
"""
if self.type == self.WAN:
m = f"msg|{self._msg_id}|"
msg = m.encode("utf-8")+msg
self._msgs[self._msg_id] = [msg, False]
self._msg_id += 1
self.sock_send(msg)
def quit(self):
"""Closes the socket and stops the listening thread"""
if self.running:
self.running = False
if self.sock:
self.sock.close()
self.sock = None