Compare commits

..

No commits in common. "792884d7b0cfd3bccaebd9cdace583609529e727" and "b7ea7ff362355850f1ab5a19615731bfe9ed333c" have entirely different histories.

4 changed files with 49 additions and 65 deletions

View File

@ -166,10 +166,6 @@ class Client:
await asyncio.sleep(0.1) await asyncio.sleep(0.1)
self.is_disconnected() self.is_disconnected()
if self.__alive: if self.__alive:
if header == b"":
self.__packets_queue.append(None)
self.__alive = False
continue
self.log.debug(f"Header: {header}") self.log.debug(f"Header: {header}")
await self.kick("Invalid packet - header negative") await self.kick("Invalid packet - header negative")
self.__packets_queue.append(None) self.__packets_queue.append(None)
@ -182,22 +178,13 @@ class Client:
self.__packets_queue.append(None) self.__packets_queue.append(None)
continue continue
data = await self.__reader.read(int_header) data = await self.__reader.read(100 * MB)
self.log.debug(f"int_header: {int_header}; data: `{data}`;")
abg = b"ABG:"
if len(data) > len(abg) and data.startswith(abg):
data = zlib.decompress(data[len(abg):])
self.log.debug(f"ABG Packet: {len(data)}")
if one: if one:
# self.log.debug(f"int_header: `{int_header}`; data: `{data}`;") self.log.debug(f"int_header: `{int_header}`; data: `{data}`;")
return data return data
# FIXME else:
# else: t = asyncio.create_task(self.__handle_packet(data, int_header))
# t = asyncio.create_task(self.__handle_packet(data, int_header)) self.__tasks.append(t)
# self.__tasks.append(t)
self.__packets_queue.append(data)
except ConnectionError: except ConnectionError:
self.__alive = False self.__alive = False
@ -289,8 +276,7 @@ class Client:
return return
def _get_cid_vid(self, data: str): def _get_cid_vid(self, data: str):
sep = data.find(":", 1) + 1 s = data[:data.find(":", 1)]
s = data[sep:sep + 3]
id_sep = s.find('-') id_sep = s.find('-')
if id_sep == -1: if id_sep == -1:
self.log.debug(f"Invalid packet: Could not parse pid/vid from packet, as there is no '-' separator: '{data}'") self.log.debug(f"Invalid packet: Could not parse pid/vid from packet, as there is no '-' separator: '{data}'")
@ -309,11 +295,11 @@ class Client:
self.log.debug(f"Invalid packet: Could not parse pid/vid from packet: '{data}'") self.log.debug(f"Invalid packet: Could not parse pid/vid from packet: '{data}'")
return -1, -1 return -1, -1
async def _handle_vehicle_codes(self, dta): async def _handle_vehicle_codes(self, data):
if len(dta) < 6: if len(data) < 6:
return return
sub_code = dta[1] sub_code = data[1]
data = dta[3:] data = data[3:]
match sub_code: match sub_code:
case "s": # Spawn car case "s": # Spawn car
self.log.debug("Trying to spawn car") self.log.debug("Trying to spawn car")
@ -351,10 +337,10 @@ class Client:
await self._send(des) await self._send(des)
case "d": # Delete car case "d": # Delete car
self.log.debug("Trying to delete car") self.log.debug("Trying to delete car")
cid, car_id = self._get_cid_vid(dta) cid, car_id = self._get_cid_vid(data)
if car_id != -1 and cid == self.cid: if car_id != -1 and cid == self.cid:
# TODO: Call event onCarDelete # TODO: Call event onCarDelete
await self._send(dta, to_all=True, to_self=True) await self._send(data, to_all=True, to_self=True)
try: try:
car = self.cars[car_id] car = self.cars[car_id]
if car['unicycle']: if car['unicycle']:
@ -369,7 +355,7 @@ class Client:
self.log.debug("Trying to edit car") self.log.debug("Trying to edit car")
allow = True allow = True
# TODO: Call event onCarEdited # TODO: Call event onCarEdited
cid, car_id = self._get_cid_vid(dta) cid, car_id = self._get_cid_vid(data)
if car_id != -1 and cid == self.cid: if car_id != -1 and cid == self.cid:
try: try:
car = self.cars[car_id] car = self.cars[car_id]
@ -377,7 +363,7 @@ class Client:
self._cars.pop(car_id) self._cars.pop(car_id)
await self._send(f"Od:{self.cid}-{car_id}", to_all=True, to_self=True) await self._send(f"Od:{self.cid}-{car_id}", to_all=True, to_self=True)
elif allow: elif allow:
await self._send(dta, to_all=True, to_self=False) await self._send(data, to_all=True, to_self=False)
if car['json_ok']: if car['json_ok']:
old_car_json = car['json'] old_car_json = car['json']
try: try:
@ -392,16 +378,16 @@ class Client:
self.log.debug(f"Unknown car: car_id={car_id}") self.log.debug(f"Unknown car: car_id={car_id}")
case "r": # Reset car case "r": # Reset car
self.log.debug("Trying to reset car") self.log.debug("Trying to reset car")
cid, car_id = self._get_cid_vid(dta) cid, car_id = self._get_cid_vid(data)
if car_id != -1 and cid == self.cid: if car_id != -1 and cid == self.cid:
# TODO: Call event onCarReset # TODO: Call event onCarReset
await self._send(dta, to_all=True, to_self=False) await self._send(data, to_all=True, to_self=False)
self.log.debug(f"Car reset: car_id={car_id}") self.log.debug(f"Car reset: car_id={car_id}")
case "t": case "t":
self.log.debug(f"Received 'Ot' packet: {dta}") self.log.debug(f"Received 'Ot' packet: {data}")
await self._send(dta, to_all=True, to_self=False) await self._send(data, to_all=True, to_self=False)
case "m": case "m":
await self._send(dta, to_all=True, to_self=True) await self._send(data, to_all=True, to_self=True)
async def _handle_codes(self, data): async def _handle_codes(self, data):
if not data: if not data:
@ -502,14 +488,9 @@ class Client:
self.__alive = False self.__alive = False
if (self.cid > 0 or self.nick is not None) and \ if (self.cid > 0 or self.nick is not None) and \
self.__Core.clients_by_nick.get(self.nick): self.__Core.clients_by_nick.get(self.nick):
for i, car in enumerate(self.cars): # if self.ready:
if not car: # await self.tcp_send(b"", to_all=True) # I'm disconnected.
continue self.log.debug(f"Removing client {self.nick}:{self.cid}")
self.log.debug(f"Removing car: car_id={i}")
await self._send(f"Od:{self.cid}-{i}", to_all=True, to_self=False)
if self.ready:
await self._send(f"J{self.nick} disconnected!", to_all=True, to_self=False) # I'm disconnected.
self.log.debug(f"Removing client")
# TODO: i18n # TODO: i18n
self.log.info("Disconnected") self.log.info("Disconnected")
self.__Core.clients[self.cid] = None self.__Core.clients[self.cid] = None

View File

@ -143,7 +143,7 @@ class TCPServer:
self.run = True self.run = True
try: try:
server = await asyncio.start_server(self.handle_client, self.host, self.port, server = await asyncio.start_server(self.handle_client, self.host, self.port,
backlog=int(config.Game["players"] * 2.3)) backlog=int(config.Game["players"] * 1.3))
self.log.debug(f"TCP server started on {server.sockets[0].getsockname()!r}") self.log.debug(f"TCP server started on {server.sockets[0].getsockname()!r}")
while True: while True:
async with server: async with server:

View File

@ -10,36 +10,42 @@ import traceback
from core import utils from core import utils
class UDPServer(asyncio.DatagramTransport): class UDPServer:
def __init__(self, core, host=None, port=None): def __init__(self, core, host, port):
super().__init__()
self.log = utils.get_logger("UDPServer") self.log = utils.get_logger("UDPServer")
self.loop = asyncio.get_event_loop() self.loop = asyncio.get_event_loop()
self.Core = core self.Core = core
self.host = host self.host = host
self.port = port self.port = port
self.run = False self.run = False
self.transport = None
def connection_made(self, transport): async def handle_client(self, reader, writer):
self.transport = transport while True:
try:
def datagram_received(self, data, addr): data = await reader.read(1)
message = data.decode() if not data:
print('Received %r from %s' % (message, addr)) break
print('Send %r to %s' % (message, addr)) code = data.decode()
self.transport.sendto(data, addr) self.log.debug(f"Received {code!r} from {writer.get_extra_info('sockname')!r}")
# await self.handle_code(code, reader, writer)
# task = asyncio.create_task(self.handle_code(code, reader, writer))
# await asyncio.wait([task], return_when=asyncio.FIRST_EXCEPTION)
if not writer.is_closing():
writer.close()
self.log.debug("Disconnected.")
break
except Exception as e:
self.log.error("Error while connecting..")
self.log.error(f"Error: {e}")
traceback.print_exc()
break
async def start(self): async def start(self):
self.log.debug("Starting UDP server.") self.log.debug("Starting UDP server.")
self.run = True self.run = True
try: try:
self.transport, _ = await self.loop.create_datagram_endpoint( pass
lambda: self,
local_addr=(self.host, self.port),
reuse_port=True
)
except OSError as e: except OSError as e:
self.log.error("Cannot bind port or other error") self.log.error("Cannot bind port or other error")
raise e raise e
@ -52,4 +58,3 @@ class UDPServer(asyncio.DatagramTransport):
def stop(self): def stop(self):
self.log.debug("Stopping UDP server") self.log.debug("Stopping UDP server")
self.transport.close()

View File

@ -5,22 +5,20 @@
# Licence: FPA # Licence: FPA
# (c) kuitoi.su 2023 # (c) kuitoi.su 2023
import asyncio import asyncio
from typing import Tuple
from core import utils from core import utils
class UDPServer: class UDPServer:
def __init__(self, core, host=None, port=None): def __init__(self, core, host, port):
self.log = utils.get_logger("UDPServer") self.log = utils.get_logger("UDPServer")
self.loop = asyncio.get_event_loop() self.loop = asyncio.get_event_loop()
self.Core = core self.Core = core
self.host = host self.host = host
self.port = port self.port = port
self.run = False self.run = False
self.transport = None async def handle_client(self, srv_sock) -> None: ...
def connection_made(self, transport: asyncio.DatagramTransport): ...
def datagram_received(self, data: bytes, addr: Tuple[str, int]): ...
async def start(self) -> None: ... async def start(self) -> None: ...
async def stop(self) -> None: ... async def stop(self) -> None: ...