您好,我正在尝试通过websocket将数据js发送到django,但无法正常工作。您能帮我哪里做错了吗?
ps:我能够将数据从服务器发送到客户端
错误:
提高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);
};
consumer.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()
答案 0 :(得分:0)
我找到了
import Web3 from 'web3';
const web3 = new Web3(window.web3.currentProvider);
export default web3;
或带有异步json
class TickTockConsumer(WebsocketConsumer):
def connect(self):
self.accept()
self.send("tick")
self.send(".......tock")
def receive(self, text_data):
print(text_data)