1

大家好,我正在尝试使用 websocket 将数据 js 发送到 django 但无法正常工作你能帮我看看我哪里做错了吗?

ps:我能够将数据从服务器发送到客户端

错误:

raise ValueError("没有用于传入 WebSocket 帧的文本部分!")

传入的 WebSocket 框架没有文本部分!

WebSocket 断开/ws/ [127.0.0.1:64282]

js

document.addEventListener('DOMContentLoaded', function () {
        let webSocketBridge = new WebSocket("ws://127.0.0.1:8000/ws/");

        webSocketBridge.onopen = function(action) {
            console.log(action);
            webSocketBridge.send(JSON.stringify({
                "id": "client1"
            }));

        };

        webSocketBridge.onmessage = function(event) {
           let message = event.data;
            as += message + "\r\n";
            $('#messages').html(as);

        };

消费者.py

import asyncio
from channels.generic.websocket import AsyncJsonWebsocketConsumer

class TickTockConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        await self.accept()

        while 1:
            await asyncio.sleep(0.1)
            await self.send_json("tick")
            await asyncio.sleep(0.1)
            await self.send_json(".......tock")
            await self.receive()
4

1 回答 1

0

我找到了

class TickTockConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()
        self.send("tick")
        self.send(".......tock")

    def receive(self, text_data):
        print(text_data)

或使用异步 json

class TickTockConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        await self.accept()
        await self.send("tick")
        await self.send(".......tock")

    async def receive(self, text_data):
        print(text_data)
于 2019-09-16T07:33:46.543 回答