ASGI
import os
from .consumer import MyConsumer
from django.urls import path
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings")
django_asgi_app = get_asgi_application()
application = ProtocolTypeRouter(
{
"http": django_asgi_app,
"websocket": AllowedHostsOriginValidator(
AuthMiddlewareStack(URLRouter([path('ws/chat/',MyConsumer.as_asgi())]))
),
}
)
*Consumer
from channels.generic.websocket import WebsocketConsumer
class MyConsumer(WebsocketConsumer):
groups = ["broadcast"]
def connect(self):
self.accept()
self.accept("subprotocol")
self.close()
def receive(self, text_data=None, bytes_data=None):
self.send(text_data="Hello world!")
self.send(bytes_data="Hello world!")
self.close()
self.close(code=4123)
def disconnect(self, close_code):
pass
Redis also tried inmemory
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("127.0.0.1", 6379)],
},
},
}
console output
WebSocket HANDSHAKING /ws/chat/ [127.0.0.1:49645]
WebSocket REJECT /ws/chat/ [127.0.0.1:49645]
WebSocket DISCONNECT /ws/chat/ [127.0.0.1:49645]