Ajay Kumar
Ajay Kumar

Reputation: 1655

Django channels websocket reconnect

I am building a messaging system in Django, using web-socket to receive the message.

Here is my tryouts,

from channels.consumer import AsyncConsumer
from channels.db import database_sync_to_async

class ChatConsumer(AsyncConsumer):

    async def websocket_connect(self, event):
        print("connected", event)
        await self.send({
            "type": "websocket.accept"
        })

    async def websocket_receive(self, event):
        print("receive", event)
        message = event['text']
        obj = await self.create_obj(message=message)
        print('Created...')

    async def websocket_disconnect(self, event):
        print("disconnected", event)

    @database_sync_to_async
    def create_obj(self, **kwargs):
        obj = ChatMessage.objects.create(message=kwargs['message'])
        return obj

When I start a client app the web-socket is connected, and i can receive the message and i am able to store into the DB.

connected {'type': 'websocket.connect'}
WebSocket CONNECT /ws/message [192.168.0.101:50148]

After some idle time, the web-socket disconnects automatically,

Application instance <Task pending coro=<SessionMiddlewareInstance.__call__() running at /Users/ajay/Desktop/workspace/projects/python/django/websock/venv/lib/python3.7/site-packages/channels/sessions.py:183> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x10b311510>()]>> for connection <WebSocketProtocol client=['192.168.0.101', 50148] path=b'/ws/message'> took too long to shut down and was killed.

After disconnects, i am not able to receive the message, when i reload the client, web-socket is connected, is there any way to reconnect the we-socket automatically with out reloading the client. I request to guide me some suggestion to achieve this, it will be very helpful for me, Thanks in advance.

Upvotes: 1

Views: 2325

Answers (1)

Yandiro
Yandiro

Reputation: 157

This is old, but this answer may help others. You can use https://www.npmjs.com/package/reconnecting-websocket

Upvotes: 0

Related Questions