gpt4 book ai didi

Django Channels - 无法在断开连接时发送消息

转载 作者:行者123 更新时间:2023-12-05 06:54:31 24 4
gpt4 key购买 nike

我希望能够在用户断开连接时向房间组发送消息,以便它更新播放器列表。似乎一旦断开连接就不可能,这在某种程度上是有道理的,但是我如何才能在断开用户连接之前向 channel 发送消息。

我有以下代码:

async def disconnect(self, close_code):
#Remove the disconnected player
player = players.get_player(self.scope['session']['id'])
players.remove_player(player.id)
room = rooms.get_room(player.room)
if room:
#Sending messages on disconnect doesn't seem to work
players_left = room.leave_room(player)
if players_left < 1:
rooms.remove_room(room.name)
await self.channel_layer.group_send(
'all_users',
{
'type': 'room_list',
}
)
await self.channel_layer.group_discard(
room.name,
self.channel_name
)
else:
await self.send_room(room,'list_players')

async def send_room(self,room,type):
await self.channel_layer.group_send(
room.name,
{
'type': type,
'data': room.name
}
)

async def list_players(self,event):
# Send message to WebSocket
room = rooms.get_room(event['data'])
players = room.get_players()
await self.send(text_data=json.dumps({
'action': 'room_list_players',
'payload' : {
'players' : players,
'owner' : room.owner.id
}
}))

最佳答案

这是一个老问题,我不知道是否还有人需要它的答案,但我在 Django Channels 3.0.1 中找到的解决方案实际上非常简单。每个 WebsocketConsumer 都定义了一个 websocket_disconnect 函数,它会在调用实际的 disconnect 函数之前删除当前分配给 websocket 的组。显然,这意味着当您断开连接时,您将无法再发送群组消息,因为没有群组。

解决方案是简单地覆盖 websocket_disconnect 并使用如下内容将您的消息发送到那里:

async def websocket_disconnect(self, message):
await self.channel_layer.group_send(
self.room_group_name,
{ 'type': 'dc_message' }
)
await super().websocket_disconnect(message)

关于Django Channels - 无法在断开连接时发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65517845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com