Skip to content

Commit

Permalink
add "on_client_connected" callback
Browse files Browse the repository at this point in the history
  • Loading branch information
Fr0stFree committed Jun 11, 2024
1 parent c8d6e0a commit 4245ded
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions server/src/server.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import asyncio
import logging.config
import uuid
import datetime as dt

from server.src.handlers import error_handler, send_message_handler, broadcast_message_handler, \
unknown_action_handler, logout_handler
from server.src.models.client import ClientManager
from server.src.models.client import ClientManager, Client
from server.src.models.request import Request
from server.src.router import Router
from server.src.settings import ServerSettings
from shared.schemas.actions import ActionFrame, ActionTypes
from shared.schemas.notifications import NotificationFrame, PrivateMessageNotificationPayload, \
PrivateMessageNotificationFrame
from shared.schemas.types import UserId


class Server:
Expand All @@ -27,7 +31,7 @@ def __init__(self, settings: ServerSettings) -> None:

async def start(self) -> None:
self._server_logger.info("Starting server on %s:%s...", self._settings.host, self._settings.port)
self._server = await asyncio.start_server(self._on_client_connected, self._settings.host, self._settings.port)
self._server = await asyncio.start_server(self._connection_callback, self._settings.host, self._settings.port)
self._server_logger.info("Server is started")

async def serve(self) -> None:
Expand All @@ -47,9 +51,10 @@ async def stop(self) -> None:
self._server = None
self._server_logger.debug("Server is stopped")

async def _on_client_connected(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
async def _connection_callback(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
client = self._clients.create(reader, writer)
self._server_logger.info("New connection from %s", client)
await self.on_client_connected(client)
while True:
raw = await client.listen()
request = Request(
Expand All @@ -61,6 +66,15 @@ async def _on_client_connected(self, reader: asyncio.StreamReader, writer: async
await self._router.handle(request)
request.logger.debug("Request '%s' has been handled", request)

async def on_client_connected(self, client: Client) -> None:
payload = PrivateMessageNotificationPayload(
text=f"Hello, {client.user.id}!",
sender=UserId("SERVER"),
to=client.user.id,
created_at=dt.datetime.now(dt.UTC),
)
await client.send(PrivateMessageNotificationFrame(payload=payload))

def _setup_routes(self, router: Router) -> None:
router.register_action_handler(ActionTypes.BROADCAST_MESSAGE, broadcast_message_handler) \
.register_action_handler(ActionTypes.SEND_MESSAGE, send_message_handler) \
Expand Down

0 comments on commit 4245ded

Please sign in to comment.