WebSocket connection error when creating a chat application with Django

Question:

I am working on a chat application which is like a whatsapp web clone. I have been stuck dealing with websocket connection as it cannot connect to the specified address. I am getting the error WebSocket connection to 'ws://127.0.0.1:8000/ws/2/' failed:. The url specified is because I am using the user id to create a room name in the consumers.py file.
Here is part of the consumers.py file:

class PersonalChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        my_id = self.scope['user'].id
        other_user_id = self.scope['url_route']['kwargs']['id']
        if int(my_id) > int(other_user_id):
            self.room_name = f'{my_id}-{other_user_id}'
        else:
            self.room_name = f'{other_user_id}-{my_id}'

        self.room_group_name = 'chat_%s' % self.room_name

        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

Inside the asgi.py file, I have this code;

application = ProtocolTypeRouter({
    'websocket': AuthMiddlewareStack(
        URLRouter([
            path('ws/<int:id>/', PersonalChatConsumer)
        ])
    )
})

Also here is part of the javascript file handling the websocket connection:

const id = JSON.parse(document.getElementById('json-username').textContent);
const message_username = JSON.parse(document.getElementById('json-message-username').textContent);

const socket = new WebSocket(
    'ws://'
    + window.location.host
    + '/ws/'
    + id
    + '/'
);

The error message in the console of VsCode states Not Found: /ws/2/.
Also here is the urls file:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include(('accounts.urls', 'accounts'), namespace='accounts')),
    path('', index, name='home'),
    path('<str:username>/', chatPage, name='chat'),
]

Any help will be highly appreciated. Thanks

Asked By: KipronoKirui

||

Answers:

I finally managed to solve the issue. I realized that everything was working fine except for the redis server. I solved it by running redis-server direct instead of using docker. Here is a link to the question that gave me the solution: Way of Avoid Docker on Django Channels

Answered By: KipronoKirui