refactor(backend_server.py): rewrite _handle_connection() to minimize indents
This commit is contained in:
@@ -164,11 +164,21 @@ class BackendServer:
|
||||
try:
|
||||
if mask & selectors.EVENT_READ:
|
||||
self._receive_inbound(sock, client)
|
||||
if client.inbound:
|
||||
if not client.inbound:
|
||||
self._disconnect(client)
|
||||
return
|
||||
|
||||
if client.mac_id is None:
|
||||
# expect HELLO message
|
||||
try:
|
||||
msg = Message.from_bytes(client.inbound)
|
||||
except Exception as e:
|
||||
self.logger.error(
|
||||
f"Failed to parse HELLO message from {client}: {e}"
|
||||
)
|
||||
self._disconnect(client)
|
||||
return
|
||||
|
||||
if (
|
||||
msg.category == Category.CONTROL
|
||||
and msg.action == ControlAction.HELLO
|
||||
@@ -180,30 +190,21 @@ class BackendServer:
|
||||
and self.clients[client.mac_id].status
|
||||
== "connected"
|
||||
):
|
||||
old_client: Client = self.clients[
|
||||
client.mac_id
|
||||
]
|
||||
old_client: Client = self.clients[client.mac_id]
|
||||
self.logger.warning(
|
||||
f"Client {client.mac_id} is already connected from {old_client.addr}, disconnecting old client..."
|
||||
)
|
||||
self._disconnect(old_client)
|
||||
self.send_close(old_client)
|
||||
# self._disconnect(old_client)
|
||||
# TODO: tell client not to reconnect
|
||||
self.clients[client.mac_id] = client
|
||||
self.logger.info(
|
||||
f"[+] Registered new client {client}"
|
||||
)
|
||||
self.logger.info(f"[+] Registered new client {client}")
|
||||
else:
|
||||
self.logger.error(
|
||||
f"Expected HELLO message from {client}, got {msg}"
|
||||
)
|
||||
self._disconnect(client)
|
||||
return
|
||||
except Exception as e:
|
||||
self.logger.error(
|
||||
f"Failed to parse HELLO message from {client}: {e}"
|
||||
)
|
||||
self._disconnect(client)
|
||||
return
|
||||
|
||||
while b"\n" in client.inbound:
|
||||
line, client.inbound = client.inbound.split(b"\n", 1)
|
||||
@@ -214,8 +215,7 @@ class BackendServer:
|
||||
msg = Message.from_bytes(line)
|
||||
self.logger.info(f"[.] Parsed message {msg.id}")
|
||||
if msg.ack_required:
|
||||
self._send_ack(client, target_id=msg.id)
|
||||
|
||||
self.send_ack(client, target_id=msg.id)
|
||||
except Exception as e:
|
||||
self.logger.error(
|
||||
f"Failed to parse message from {client}: {e}"
|
||||
@@ -223,11 +223,7 @@ class BackendServer:
|
||||
self._disconnect(client)
|
||||
return
|
||||
|
||||
else:
|
||||
self._disconnect(client)
|
||||
|
||||
if mask & selectors.EVENT_WRITE:
|
||||
if client.outbound:
|
||||
if mask & selectors.EVENT_WRITE and client.outbound:
|
||||
self._send_outbound(sock, client)
|
||||
|
||||
except ConnectionResetError as e:
|
||||
|
||||
Reference in New Issue
Block a user