繁体   English   中英

Django 通道 websocket 不接收发送的数据

[英]Django channels websocket not receiving data sent

我目前正在学习如何使用 Django 通道进行 websocket 连接,到目前为止我已经让 websocket 实际连接,但是当我发送数据时它没有收到它。

这是我的consumers.py

class WSConsumer(AsyncConsumer):
    async def websocket_connect(self, event):
        print('connected', event)
        await self.send({
            'type': 'websocket.accept'
        })
        await self.send({
            'type': 'websocket.send',
            'message': 'TEST'
        })
        print('sent')

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

    async def websocket_receive(self, event):
        print('received', event))

这是我在前端的 javascript

    const roomName = JSON.parse(document.getElementById('room-name').textContent);

    const WSocket = new WebSocket(
        'ws://'
        + window.location.host
        + '/ws/room/'
        + roomName
        + '/'
    );

    WSocket.onopen = function(e) {
        console.log('websocket has connected');
    };

    WSocket.onmessage = function(e) {
        console.log(e);
    };


    WSocket.onclose = function(e) {
        console.error('websocket closed unexpectedly');
    };

Woops 才意识到我是个男人的傻瓜。

在我最初写的下面的代码中

        await self.send({
            'type': 'websocket.send',
            'message': 'TEST'
        })

什么时候应该

        await self.send({
            'type': 'websocket.send',
            'text': 'TEST'
        })

它应该有一个“文本”类型而不是“消息”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM