django channels 实现通讯

本文详细介绍使用Django Channels实现实时双向通讯的过程,包括如何创建ChatConsumer类处理WebSocket连接,加入和离开群组,接收及发送消息。同时,演示了如何通过监听数据库模型状态变化,向指定频道内用户发送通知。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于channels配置官网上有详细的示范案列直接拉下来用即可

from channels.generic.websocket import AsyncWebsocketConsumer
import json

class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name

        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        # Send message to room group
        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message
            }
        )

    # Receive message from room group
    async def chat_message(self, event):
        message = event['message']

        # Send message to WebSocket
        await self.send(text_data=json.dumps({
            'message': message
        }))

现在的代码就可以实现双方连接到频道内的通讯功能

例如要实现消息的通知

@receiver(post_save, sender=chat)
def send_chat(sender, instance, **kwargs):
    notifications = instance.receiver.received_chat.filter(read_status=0)
    channel_layer = get_channel_layer() # 调用channels
    count = notifications.count()  # 例如通知的个数
	 #我们可以监听数据库的模型的状态来给评到内的所有用户发送一个通知
    async_to_sync(channel_layer.group_send)('chat_%s' % instance.receiver.id,
                                            {'type': 'notificate.message', 'count': count})
    # chat_%s xxxxxxxx 表示self.room_group_name 房间号

# 然后就是消息的保存mysql来做存储的                                       
	async def receive(self, text_data):  # 在接收消息的时候可以做一些消息的存储
        if text_data_json['chat_type'] in ['0']:
        # 用处理数据调用channels 中的database_sync_to_async 数据库处理方式来处理
            database_sync_to_async(self.save_message(text_data_json))        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值