今天,我们来实现一下群聊功能,其实和昨天的一对一聊天一样,只是在原有的代码上做一些修改,话不多说,进入到我们今天的课程。
首先,需要下载一个插件:pip3 install channels-redis == 3.4.0
下载好之后,我们配置一下redis
在setting.py里
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [('127.0.0.1', 6379)]
},
},
}
值得注意的是,这个redis版本一定要是5.0的,其余都不支持
版本低的话小伙伴们可以到官网下载,复制以下链接进入到redis官网
https://github.com/tporadowski/redis/releases
然后在主文件里的consumer.py写入以下代码
import json
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
from asgiref.sync import async_to_sync
CONN_LIST = []
class ChatConsumer(WebsocketConsumer):
def websocket_connect(self, message):
# 接收这个客户端的连接
self.accept()
print("1111111111",message)
CONN_LIST.append(self)
# 将这个客户端的连接对象加入到某个地方(内存 or redis)1314 是群号这里写死了
# async_to_sync(self.channel_layer.group_add)('1314', self.channel_name)
def websocket_receive(self, message):
# 通知组内的所有客户端,执行 xx_oo 方法,在此方法中自己可以去定义任意的功能。
print("222222222222",message)
data = json.loads(message.get('text','{}'))
chat_type = data.get('chat_type')
chat_id = data.get('chat_id')
chat_content = data.get('message')
#创建聊天群组
print("chat_type>>>>>",type(chat_type))
if chat_type == "add_chat":
async_to_sync(self.channel_layer.group_add)(chat_id, self.channel_name)
else:
async_to_sync(self.channel_layer.group_send)(chat_id, {'type':"chat.message","message":message})
# async_to_sync(self.channel_layer.group_send)('1314', {"type": "xx.oo", 'message': message})
# 这个方法对应上面的type,意为向1314组中的所有对象发送信息
def chat_message(self, event):
print("hahahahahaa")
text = event['message']['text']
self.send(text)
def websocket_disconnect(self, message):
print("3333333",message)
data = json.loads(message['text'])
chat_id = data.get('chat_id')
# 断开链接要将这个对象从 channel_layer 中移除
async_to_sync(self.channel_layer.group_discard)(chat_id,self.channel_name)
raise StopConsumer()
这样写完之后,后端就完成了,接下来看前端。
多组群聊
值得一提的是用户名和用户id一定要从localStorage里获取,登陆的时候获取token并存入localStorage就可以了。



