大家好,我正在尝试使用 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()