1

my application like this

# asgi.py
import os

from django.core.asgi import get_asgi_application
from websocket_app.websocket import websocket_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'websocket_app.settings')

django_application = get_asgi_application()


async def application(scope, receive, send):
    if scope['type'] == 'http':
        # Let Django handle HTTP requests
        await django_application(scope, receive, send)
    elif scope['type'] == 'websocket':
        # handle websocket connections here
        await websocket_application(scope, receive, send)
    else:
        raise NotImplementedError(f"Unknown scope type { scope['type'] }")

# websocket.py
async def websocket_application(scope, receive, send):
    while True:
        event = await receive()

        if event['type'] == 'websocket.connect':
            await send({
                "type": "websocket.accept"
            })

        if event['type'] == 'websocket.disconnect':
            break

        if event['type'] == 'websocket.receive':
            try:
                # result = json.loads(event['text'])
                await route(scope, event, send)
            except Exception as e:
                await send({
                    "type": "websocket.send",
                    "text": e.__repr__()
                })

I want to send a message to A client when I received a message from B client, but i have no idea how can I find a websocket connection and send message to A client.

I think I should do something to manage multiple websocket connection, but I have no idea how to do it.

pppppu
  • 33
  • 3

0 Answers0