我正在尝试构建一个实时机票预订应用程序,因此我想向用户显示实时座位预订状态。
例如; 我有user1
并user2
连接到一个组reservation-1
Now when the user1
selects the ticket in group reservation-1
the seat status will be converted to selected and the message should be broadcasted to all the users connected to the same group with the status of unavailable for that particular seat. 但对于 user1,它应该是选中的状态。
我的 JavaScript 代码实现:
const socket = new WebSocket('ws://${window.location.host}/ws/reservation-1');
const seats = document.querySelectorAll('.seats');
seats.forEach(seat => {
seat.addEventListener('click', () => {
if(seat.dataset.isSelected) {
// This is an event when user select the seat
socket.send(JSON.stringify({
"event": "SELECT",
"seat": "seat_id"
}));
}else {
// This is an event when user deselect the seat
socket.send(JSON.stringify({
"event": "DESELECT",
"seat": "seat_id"
}));
}
}
});
socket.onmessage = function(e) {
const data = JSON.parse(e.data);
// code logic to update the seat based on return values of seat status.
}
我使用 django-channels 的 Django 服务器端消费者代码:
import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
class ReservationConsumer(WebsocketConsumer):
def connect(self):
self.chat_group_name = 'reservation-1'
async_to_sync(self.channel_layer.group_add)(
self.reservation_group_name,
self.channel_name
)
self.accept()
def disconnect(self, close_code):
async_to_sync(self.channel_layer.group_discard)(
self.reservation_group_name,
self.channel_name
)
def receive(self, text_data):
data = json.loads(text_data)
user = self.scope['user']
event = data['event']
seat_id = data['seat_id']
if event == 'SELECT':
# this code saves the seat status as selected in database
save_seat_status_to_selected(user, seat_id)
if event == 'DESELECT':
# this code saves the seat status as selected in database
remove_the_seat_status_of_selected(user, seat_id)
# this code is now sending a group message to all the users connected to the group.
# I now want to differentiate the message based on the user who selected the seat
# to pass only selected status to the event emitter and the rest of the user with the reserved
async_to_sync(self.channel_layer.group_send)(
self.reservation_group_name,
{
# get_reserved_seat will get all the seat status that are in reserved state and also the seat selected by other users
'reserved': get_reserved_seat(),
# get_selected_seat will get the seat selected by the user
'selected': get_selected_seat(user)
}
)
我正在使用 channel_redis 进行群组消息传递。我对通道层的设置配置是:
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
更新
我正在使用 django-channels-presence 来确定用户在同一组(房间)中的连接。有没有办法向同一个连接组中的每个用户发送特定消息?
高度赞赏有关可扩展的更好代码实现的建议。