DJAMA Med
DJAMA Med

Reputation: 119

Error message "WebSocket HANDSHAKING - WebSocket REJECT - WebSocket DISCONNECT" in Django Channels

I recently followed the official Django Channels documentation (version 4.0.0) to set up WebSockets in my Django project. I've gone through the documentation tutorial and configured my project correctly. However, when I attempt to test the service using websocketking, I'm encountering a handshaking issue.

Here are some details about my configuration:

  1. My asgi.py file looks like this:
import os
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", "schatai.settings")
django_asgi_app = get_asgi_application()

import schatai.routing

application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(URLRouter(schatai.routing.websocket_urlpatterns))
        ),
    }
)
  1. My consumers.py file looks like this:
import json

from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer

class WsTestConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()

    def disconnect(self, close_code):
        pass

    # Receive message from WebSocket
    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json["message"]

        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name, {"type": "chat_message", "message": message}
        )

    # Receive message from room group
    def chat_message(self, event):
        message = event["message"]

        # Send message to WebSocket
        self.send(text_data=json.dumps({"message": message}))
  1. My routing.py file looks like this:
from django.urls import re_path, path

from . import consumers

websocket_urlpatterns = [
    re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.SchataiConsumer.as_asgi()),
    path(r"ws/", consumers.WsTestConsumer.as_asgi()),
]
  1. I've also configured my settings.py file in accordance with the documentation.

When I run the python manage.py runserver command, the server starts successfully on ASGI.

However, when I attempt to test my service using websocketking, I receive the following error message:

WebSocket HANDSHAKING /ws/ [127.0.0.1:48198]
WebSocket REJECT /ws/ [127.0.0.1:48198]
WebSocket DISCONNECT /ws/ [127.0.0.1:48198]

I'd like to know if anyone has encountered this issue before or if they have any ideas about what might be causing this handshaking problem. Any help or suggestions would be greatly appreciated.

Thank you in advance for your assistance!

Upvotes: 2

Views: 1158

Answers (2)

Olamigoke Philip
Olamigoke Philip

Reputation: 1157

If you're still encountering issues with WebSocket disconnections after the handshake, even after trying all other steps, ensure that your WebSocket routing.py file is also correctly configured.

Example given from the Django Channels official documentation.

In earlier versions, such as Channels 2.x, the following setup would suffice:

...
websocket_urlpatterns = [
    re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer),
]

But in newer versions, missing .as_asgi() will prevent the WebSocket from connecting properly. For newer versions:

...
websocket_urlpatterns = [
    re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatConsumer.as_asgi()),
]

I noticed this myself when i tried upgrading an existing application. Cheers!

Upvotes: 0

DJAMA Med
DJAMA Med

Reputation: 119

After encountering the handshaking problem with Django Channels and conducting thorough research, I've been able to resolve this issue. Here's the solution I found:

The error message "WebSocket HANDSHAKING" followed by "WebSocket REJECT" indicates that the WebSocket server couldn't accept the connection. This can be due to several reasons, but one common cause is incorrect configuration of allowed origins (AllowedHosts) in Django.

To resolve this issue, follow these steps:

  1. Open your Django project's settings.py file.

  2. Ensure that the ALLOWED_HOSTS variable is correctly configured to include the IP address or domain name you're using for your application. For example:

    ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'websocketking.com']

  3. Restart your Django server to apply the new changes.

It's ok. Here is the documentation that helped me

Upvotes: 4

Related Questions