skip to Main Content

I am trying to create a socket-based application using Django-Channels, but I have a problem with connection to the WebSocket. To showcase my problem I created a test project.

The error message from the JS Console:

WebSocket connection to ‘ws://127.0.0.1:8000/’ failed:

The error appears to happen on the line 25 of the html file, which is creating an instance of a WebSocket()

Screenshot of the error

1

Here is the code:

# consumers.py

import ...


class ChatConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        self.groupname = 'dashboard'
        await self.channel_layer.group_add(
            self.groupname,
            self.channel_name,
        )
        await self.accept()

    ...
# routing.py

import...

websocket_urlpatterns = [
    path("", ChatConsumer.as_asgi()),
]
# views.py

import ...


def chatPage(request, *args, **kwargs):
    context = {}
    return render(request, "chatPage.html", context)
# asgi.py

import ...

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

application = ProtocolTypeRouter(
    {
        "http": get_asgi_application(),
        "websocket": AuthMiddlewareStack(
            URLRouter(
                routing.websocket_urlpatterns
            )
        )
    }
)
# settings.py

...
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels.layers.InMemoryChannelLayer"
    }
}
...
<!--chatPage.html-->

...
    <script>
      const chatSocket = new WebSocket("ws://" + window.location.host + "/");

      document.querySelector("#id_message_send_input").focus();
      document.querySelector("#id_message_send_input").onkeyup = function (e) {
        if (e.keyCode === 13) {
          document.querySelector("#id_message_send_button").click();
        }
      };
      document.querySelector("#id_message_send_button").onclick = function (e) {
          const messageInput = document.querySelector(
              "#id_message_send_input"
          ).value;
          chatSocket.send(JSON.stringify({ message: messageInput, username : "{{request.user.username}}"}));
      };
      chatSocket.onmessage = function (e) {
        const data = JSON.parse(e.data);
        const div = document.createElement("div");
        div.innerHTML = data.username + " : " + data.message;
        document.querySelector("#id_message_send_input").value = "";
        document.querySelector("#id_chat_item_container").appendChild(div);
      };
    </script>
...

After some research I found out that the channel layers might not work correctly, but I’m not sure if this is the case and if so, would like to know the ways to fix it.

P.S. I’m currently working on windows, so I don’t use redis, still I’m not sure that the same problem won’t appear when I switch to redis.

2

Answers


  1. For me downgrading the django channels package seemed to work.

    pip uninstall channels
    pip install channels==3.0.5
    
    Login or Signup to reply.
  2. Channels 4.0.0 does not start the ASGI server by default.

    If you look at your logs of the server starting you are probably seeing:

    Starting development server at http://0.0.0.0:8000/
    

    Try adding ‘daphne’ to your INSTALLED_APPS in settings.py.

    Now when your server starts you should see something like:

    Starting ASGI/Daphne version 4.0.0 development server at http://0.0.0.0:8000/
    

    See the Channels 4.0.0 release notes for more info – https://channels.readthedocs.io/en/stable/releases/4.0.0.html?highlight=INSTALLED_APPS#release-notes

    This worked for me and means you don’t need to go to an old version of Channels.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search