Habiba
Habiba

Reputation: 31

WebSocket is closed before the connection is established in Django

I am making a chat application in Django. I am following a YouTube tutorial and for most part the application is working fine, but there is some problem with my routings.

When the name of the room is a single word like "room1", the Websocket is connected and I can send and receive messages. But when name of room is made or two or more words like "habiba room", the connection is not establishing.

in console I get this error

WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/habiba%20room/' failed: WebSocket is closed before the connection is established.

and on server I get this error

WebSocket DISCONNECT /ws/chat/habiba%20room/ [127.0.0.1:62063]
[Failure instance: Traceback: <class 'ValueError'>: No route found for path 'ws/chat/habiba room/'.
E:\New folder\env\lib\site-packages\autobahn\websocket\protocol.py:2839:processHandshake
E:\New folder\env\lib\site-packages\txaio\tx.py:366:as_future
E:\New folder\env\lib\site-packages\twisted\internet\defer.py:151:maybeDeferred
E:\New folder\env\lib\site-packages\daphne\ws_protocol.py:72:onConnect
--- <exception caught here> ---
E:\New folder\env\lib\site-packages\twisted\internet\defer.py:151:maybeDeferred
E:\New folder\env\lib\site-packages\daphne\server.py:200:create_application
E:\New folder\env\lib\site-packages\channels\staticfiles.py:41:__call__
E:\New folder\env\lib\site-packages\channels\routing.py:54:__call__
E:\New folder\env\lib\site-packages\channels\sessions.py:47:__call__
E:\New folder\env\lib\site-packages\channels\sessions.py:145:__call__
E:\New folder\env\lib\site-packages\channels\sessions.py:169:__init__
E:\New folder\env\lib\site-packages\channels\middleware.py:31:__call__
E:\New folder\env\lib\site-packages\channels\routing.py:150:__call__
]

in project/routing.py

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import chat.routing

application = ProtocolTypeRouter({
    # (http->django views is added by default)
    'websocket': AuthMiddlewareStack(
        URLRouter(
            chat.routing.websocket_urlpatterns
        )
    ),
})

in chat/routing.py

# chat/routing.py
from django.urls import re_path

from . import consumers

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

in my index.js

var roomName = {{ room_name_json }};
var chatSocket = new ReconnectingWebSocket(
            'ws://' + window.location.host +
            '/ws/chat/' + roomName + '/');
    

I tried to change chat/routing.py to

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

But then I get this error

WebSocket DISCONNECT /ws/chat/habiba%20room/ [127.0.0.1:62327]
WebSocket HANDSHAKING /ws/chat/habiba%20room/ [127.0.0.1:62345]
Exception inside application: Group name must be a valid unicode string containing only ASCII alphanumerics, hyphens, or periods.
Traceback (most recent call last):
  File "E:\New folder\env\lib\site-packages\channels\sessions.py", line 183, in __call__
    return await self.inner(receive, self.send)
  File "E:\New folder\env\lib\site-packages\channels\middleware.py", line 41, in coroutine_call
    await inner_instance(receive, send)
  File "E:\New folder\env\lib\site-packages\channels\consumer.py", line 58, in __call__
    await await_many_dispatch(
  File "E:\New folder\env\lib\site-packages\channels\utils.py", line 51, in await_many_dispatch
    await dispatch(result)
  File "E:\New folder\env\lib\site-packages\asgiref\sync.py", line 296, in __call__
    ret = await asyncio.wait_for(future, timeout=None)
  File "c:\users\roshan\appdata\local\programs\python\python39\lib\asyncio\tasks.py", line 440, in wait_for
    return await fut
  File "c:\users\roshan\appdata\local\programs\python\python39\lib\concurrent\futures\thread.py", line 52, in run
    result = self.fn(*self.args, **self.kwargs)
  File "E:\New folder\env\lib\site-packages\channels\db.py", line 14, in thread_handler
    return super().thread_handler(loop, *args, **kwargs)
  File "E:\New folder\env\lib\site-packages\asgiref\sync.py", line 334, in thread_handler
    return func(*args, **kwargs)
  File "E:\New folder\env\lib\site-packages\channels\consumer.py", line 105, in dispatch
    handler(message)
  File "E:\New folder\env\lib\site-packages\channels\generic\websocket.py", line 39, in websocket_connect
    self.connect()
  File "E:\New folder\serendipity\chat\consumers.py", line 55, in connect
    async_to_sync( self.channel_layer.group_add)(
  File "E:\New folder\env\lib\site-packages\asgiref\sync.py", line 139, in __call__
    return call_result.result()
  File "c:\users\roshan\appdata\local\programs\python\python39\lib\concurrent\futures\_base.py", line 433, in result
    return self.__get_result()
  File "c:\users\roshan\appdata\local\programs\python\python39\lib\concurrent\futures\_base.py", line 389, in __get_result
    raise self._exception
  File "E:\New folder\env\lib\site-packages\asgiref\sync.py", line 204, in main_wrap
    result = await self.awaitable(*args, **kwargs)
  File "E:\New folder\env\lib\site-packages\channels_redis\core.py", line 618, in group_add
    assert self.valid_group_name(group), "Group name not valid"
  File "E:\New folder\env\lib\site-packages\channels\layers.py", line 167, in valid_group_name
    raise TypeError(
TypeError: Group name must be a valid unicode string containing only ASCII alphanumerics, hyphens, or periods.

Can someone please help me with this? Thank you a lot in advance!

Upvotes: 2

Views: 1770

Answers (1)

Debdut Goswami
Debdut Goswami

Reputation: 1379

The problem is with your regex. Note the url in your traceback. I shows /ws/chat/habiba%20room/ which it has %20 which is basically the url safe version of whitespace. You need to adjust the url in similar manner.

The same is described in traceback as TypeError: Group name must be a valid unicode string containing only ASCII alphanumerics, hyphens, or periods.

Adjust your regex or decode the parameter before capturing. I believe changing the regex is going to be a better option.

You can simply do

path('ws/chat/<room_name>/', consumers.ChatConsumer),

This should work fine but i guess you need to still decode it inside your consumers.py file.

Upvotes: 1

Related Questions