Hello everyone I know this is the third time I am asking questions about websocket, I have implemented websocket that works fine, I can send a receive message. The issue I have is that I want check the message sent if the username and id is part of the message then the message will be success. I have search many blogs and articles like this also read a lot on WebSocket but all of these didn’t solve my issue, please help.
here is an example of a valid message that works fine
{
"username": "John",
"message": 146054156041144154
}
however anything I pass here it will also succeed that is not a good idea I think
consumer.py
class QRCodeConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.group_name = "Welcome"
session_name = self.scope['url_route']['kwargs']['session_name']
self.group_name = "{}_{}".format(self.group_name, session_name)
await self.channel_layer.group_add(self.group_name, self.channel_name)
await self.accept()
async def disconnect(self, close_code):
await self.channel_layer.group_discard(self.group_name, self.channel_name)
# This function receive messages from WebSocket.
async def receive(self, text_data=None, bytes_data=None):
text_data_json = json.loads(text_data)
await self.channel_layer.group_send(
self.group_name,
{
"type": "message",
"message": text_data_json
},
)
# Receive message from room group.
async def qr_code_message(self, event):
# send message and username of sender to websocket
await self.send(
text_data=json.dumps(
{
"message": event['message'],
}
)
)
here is html file
const socket = new WebSocket("{{ ws_url }}");
let timer = null;
socket.onopen = () => {
console.log("Connection Open")
};
socket.onmessage = function (evt) {
console.log(evt["data"]);
var data = JSON.parse(evt.data);
var message = data['message']
document.getElementById("success_message").innerHTML = message;
window.location.href =
"{{ request.scheme }}://{{ request.get_host }}/success_mobile/";
};
socket.onclose = socket.onerror = () => {
console.log("WebSocket connection closed.")
};
socket.onerror = (error) => {
console.error("WebSocket error:", error);
};
Thank you for your help