django-channels webSocketBridge 读取消费者发送的数据

django-channels webSocketBridge read data sent by consumers

我正在使用测试通道 2.0 进行简单设置。

我有一个使用三种方法的路由消费者: consumers.py

from channels.generic.websocket import JsonWebsocketConsumer
from datetime import datetime

#  
class Feedback_001_Consumer(JsonWebsocketConsumer):

    def connect(self,text_data=None, bytes_data=None):
        self.accept()
        self.send_json("Connection for Feedback 1 ready.")
    #
    def receive(self,text_data=None):
        #self.accept()
        self.send_json("{}".format(datetime.now()))
        print(datetime.now())
    #
    def disconnect(self,close_code):
        pass

我的 js 看起来像这样:

const webSocketBridge = new channels.WebSocketBridge();
#...
webSocketBridge.connect('my_route/etc...');
#...
console.log(webSocketBridge.send(''));

虽然日期时间正在控制台中打印,但我无法在消费者的 receive method 中获取 self.send_json 发送的日期时间。这样做的正确方法是什么?

consumer.py

from channels.generic.websocket import JsonWebsocketConsumer
from datetime import datetime

class Feedback_001_Consumer(JsonWebsocketConsumer):
    def connect(self):
        self.accept()

    def receive_json(self, content, **kwargs):
        if content['command'] == 'time':
            time = datetime.now()
            self.send_json({'time': time})
            print(time)

    def disconnect(self,close_code):
        pass

your.js

webSocketBridge.socket.onopen = function(){
    console.log('connected to server');
// do something else. eg
    webSocketBridge.send({'command': 'time'}) 
};

webSocketBridge.listen(function(message, stream){
    var data = message.time
    console.log(data)
});