Reputation: 657
I am having a simple setup with testing channels 2.0.
I have a routed consumer with three methods: 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
and my js looks like this:
const webSocketBridge = new channels.WebSocketBridge();
#...
webSocketBridge.connect('my_route/etc...');
#...
console.log(webSocketBridge.send(''));
While the datetime is printing in the console, I cannot get the one sent by self.send_json
in the receive method
of the consumer. What would be the proper way to do this?
Upvotes: 2
Views: 962
Reputation: 106
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)
});
Upvotes: 2