Django通道-为什么我不能在WebSocket_DisConnect方法中从js接收数据?

ivqmmu1c  于 2022-09-18  发布在  Java
关注(0)|答案(1)|浏览(141)

我有一个聊天应用程序,我想实现一个功能,使所有消息时,某个用户从活动聊天断开连接时阅读。我可以通过self.scope['user']获取用户,但我不知道如何从chatroom.js获取活动聊天。

我的代码是:

consumers.py

class ChatConsumer(AsyncConsumer):
    async def websocket_connect(self, event):
        print('connected', event)
        ...

    async def websocket_receive(self, event):
        print('receive', event)
        ...

    async def websocket_disconnect(self, event):
        print('disconnect', event)
        received_data = json.loads(event['text'])
        user = self.scope['user']

        chat_id = received_data.get('chat_id')
        chat_obj = await self.get_thread(chat_id)
        await self.disconnect_update_read_status(chat_obj, user)

chatroom.js

let loc = window.location
let wsStart = 'ws://'

if(loc.protocol === 'https') {
    wsStart = 'wss://'
}
let endpoint = wsStart + loc.host + loc.pathname

var socket = new WebSocket(endpoint)

socket.onopen = async function(e){
    console.log('open', e)
    ...
}

socket.onmessage = async function(e){
    console.log('message', e)
    ...
}

socket.onerror = async function(e){
    console.log('error', e)
}

socket.onclose = async function(e){
    console.log('close', e)
    let thread_id = get_active_thread_id()

    let data = {
        'chat_id': thread_id
    }
    data = JSON.stringify(data)
    socket.send(data)
}

我尝试了这个解决方案,但有一个错误,当断开WebSocket连接时没有收到数据:

disconnect {'type': 'websocket.disconnect', 'code': 1001}
WebSocket DISCONNECT /chat/ [172.20.0.1:54750]
Exception inside application: 'text'
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in __call__
...
File "/usr/src/auto_store/chat/consumers.py", line 88, in websocket_disconnect received_data = json.loads(event['text'])
KeyError: 'text'

谢谢你的帮助

pepwfjgg

pepwfjgg1#

你好像打错了字。这行应该是:

json.loads(event)['text']

而不是

json.loads(event['text'])

也没有任何"text"传入该事件。完全没有。

如你所见,从

disconnect {'type': 'websocket.disconnect', 'code': 1001}

相关问题