I am trying to connect django channel 3 but it is connection rejected

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]

Well, there’s a lot that can be the root cause of your issue.

Since you have:

  • AllowedHostsOriginValidator activated, what are your ALLOWED_HOSTS setting?
  • AuthMiddlewareStack activated, are you logged in?

This appears to be a duplicate of I am trying to connect django channel but it is rejected my request and a comment you made in a separate thread.

Please do not spam this forum with repeated requests for assistance on the same topic. If you have additional information to provide, post that information as comments on the original thread.

See FAQ - Django Forum