By following Django Channel documentation I successfully ran a simple app that can two way communicate between client and server. I have three pages with a button and variable (c1,c2,c3) respectively and whose initial values are zero, and one another display page to display all three variables in real-time.
Now I want to update the variable by each client and display them in the display page. Each client will access the page which just have a button whenever they press their variable will be updated by max (c1,c2,c3) +1. All three clients can independently control their buttons thru individual pages and the result is displayed in real-time.
Any help on this will be appreciated.
My consumer.py:
import json
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.room_group_name = 'test'
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type':'chat_message',
'message':message
}
)
def chat_message(self, event):
message = event['message']
self.send(text_data=json.dumps({
'type':'chat',
'message':message
}))
And my template file is:
<h1>Live score</h1>
<form id="form">
<input type="text" name="message"/>
</form>
<div id="messages"></div>
<script type="text/javascript">
let url = `ws://${window.location.host}/ws/socket-server/`
const chatSocket = new WebSocket(url)
chatSocket.onmessage = function(e){
let data = JSON.parse(e.data)
console.log('Data:', data)
if(data.type === 'chat'){
let messages = document.getElementById('messages')
messages.insertAdjacentHTML('beforeend', `<div>
<p>${data.message}</p>
</div>`)
}
}
let form = document.getElementById('form')
form.addEventListener('submit', (e)=> {
e.preventDefault()
let message = e.target.message.value
chatSocket.send(JSON.stringify({
'message':message
}))
form.reset()
})
</script>