Django渠道websocket重新连接 [英] Django channels websocket reconnect

查看:116
本文介绍了Django渠道websocket重新连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Django中构建一个消息传递系统,使用网络套接字来接收消息.

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

这是我的尝试,

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

当我启动一个客户端应用程序时,Web套接字已连接,并且我可以接收到消息并且可以存储到数据库中.

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.

断开连接后,我无法接收消息,当我重新加载客户端时,Web-socket已连接,有什么方法可以自动重新连接we-socket而无需重新加载客户端.我要求指导我一些建议以实现这一目标,这对我将非常有帮助,在此先感谢您.

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.

推荐答案

看来您的客户端终止了连接.当用作客户端导入websocket时,我会遇到相同的问题."

it seems your client kill the connection.I face the same problem when use as client import websockets".

 # part of Client Code in the main while loop
 while not self.finished:
        try:
            self.websocket = await websockets.client.connect(
                self.connect_url,
                max_size=None,
                extra_headers=self.extra_headers
            )
.....
# in your`s producer
.......
 while True:
        # Make sure connection is still live.
        pong_waiter = await self.websocket.ping()
        await pong_waiter # if you will not await in 10-20 sec connection will close.

这篇关于Django渠道websocket重新连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆