I'm currently learning how to use Django channels for websocket connections and so far I've gotten the websocket to actually connect, but when I send it data it doesn't receive it.
This is my consumers.py
class WSConsumer(AsyncConsumer):
async def websocket_connect(self, event):
print('connected', event)
await self.send({
'type': 'websocket.accept'
})
await self.send({
'type': 'websocket.send',
'message': 'TEST'
})
print('sent')
async def websocket_disconnect(self, event):
print('disconnected', event)
async def websocket_receive(self, event):
print('received', event))
This is my javascript on the front end
const roomName = JSON.parse(document.getElementById('room-name').textContent);
const WSocket = new WebSocket(
'ws://'
+ window.location.host
+ '/ws/room/'
+ roomName
+ '/'
);
WSocket.onopen = function(e) {
console.log('websocket has connected');
};
WSocket.onmessage = function(e) {
console.log(e);
};
WSocket.onclose = function(e) {
console.error('websocket closed unexpectedly');
};
Woops just realized I'm a fool in a man's shoes.
In the below code I originally wrote
await self.send({
'type': 'websocket.send',
'message': 'TEST'
})
when it should be
await self.send({
'type': 'websocket.send',
'text': 'TEST'
})
It should have a 'text' type instead of 'message'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.