今天,我们来实现一下群聊功能,其实和昨天的一对一聊天一样,只是在原有的代码上做一些修改,话不多说,进入到我们今天的课程。

首先,需要下载一个插件: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()

这样写完之后,后端就完成了,接下来看前端。

<template><div><h2>多组群聊</h2><div><div class="message" id="message"></div><div v-show="add_chat"><input type="text" placeholder="请输入群聊id" id="txt" v-model="chat_id"><input type="button" value="加入群聊" @click="addChat()"></div><div v-show="send_chat"><m-chat ref="mChat" :messages="messages" @submit="submit" :loadMore="loadMore" height="100vh" :openExtends="open_extends"></m-chat></div></div></div>
</template><script>
// import MChat from '@maybecode/m-chat'
export default {data(){return {user_id: localStorage.getItem("user_id"),user_name:localStorage.getItem("name"),send_data: '',chat_id: null,send_chat: false,add_chat: true,messages: [],open_extends: ['image']}},methods:{submit(content) {this.sendMessage(content['content'])},loadMore() {},// 加入群聊,如果有对应的id,进入群聊,没有则创建一个新的群聊addChat() {if (this.chat_id) {this.initWebSocket()this.send_chat = truethis.add_chat = false} else {alert('请输入群聊号')}},initWebSocket() {//初始化websocket      var wsuri = "ws://127.0.0.1:8000";// var ws_scheme = window.location.protocol === "https:" ? "wss" : "ws";var ws_on_line = wsuri + '/ws/chat/'// 本地走代理/vue.config.js,线上也代理nginx代理console.log('111111111111', ws_on_line)// var ws_scheme = window.location.protocol==="https:"?"wss":"ws"      this.websock = new WebSocket(ws_on_line);this.websock.onopen = this.websocket_onopen;this.websock.onmessage = this.websocket_onmessage;this.websock.onerror = this.websocket_onerror;// this.websock.onclose = this.websocketclose;   },websocket_onopen() {//连接建立之后执行send方法发送数据     console.log("建立连接");var actions = { message: "连接测试" };var type = 'add_chat'this.sendMessage(actions, type);},websocket_onerror(e) {//连接建立失败重连      console.log("连接error", e);// this.initWebSocket();},websocket_onmessage(e) {//数据接收      this.websocket_data = JSON.parse(e.data);console.log("websocket-res", JSON.stringify(this.websocket_data))console.log("接收后端数据type", typeof (this.websocket_data))// 将websocket消息展示在消息提示框 // 发送消息人的user_idlet message_user_id = this.websocket_data['user_id']let message_self = false// 判断消息是否是自己发出if (message_user_id == this.user_id){message_self = true}// 当前消息的发送者let name = this.websocket_data.user_namevar count = this.messages.lengththis.messages.push({ type: 'text', content: {text: JSON.stringify(this.websocket_data.message) }, id: count + 1, self: message_self, name: name})var h = this.$createElement;// 创建html元素      this.hrender = h("p", null, [h("div", [h("div",JSON.stringify(this.websocket_data.message)),// 传变量           //   },         // }),           ],null),]);},sendMessage(Data, type = 'send_data') {//数据发送     console.log('222222222222')this.websock.send(JSON.stringify({ chat_id: this.chat_id, message: Data, chat_type: type, user_name:this.user_name,user_id :this.user_id}));},websocketclose(e) {  //关闭      console.log('断开连接', e);},},mounted(){}
}
</script><style></style>

值得一提的是用户名和用户id一定要从localStorage里获取,登陆的时候获取token并存入localStorage就可以了。

Django+Vue实现群聊相关推荐

  1. django+vue3实现websocket聊天室(群聊)

    1.如何实现聊天功能 2.什么是websocket 2.1解释什么叫全双工,半双工,单工 3.websocker的概念 4.websocket的优点 5.django ,vue如何实现websocke ...

  2. Node + WebSocket + Vue 聊天室创建群聊/加入群聊功能 – 第五章

    前言 本次算是做了一个小小的专题吧,"Nodejs + WebSocket + Vue实现聊天室功能",目前还在一步一步推进,之前已经可以一对一.一对多聊天了,今天就来创建群聊组, ...

  3. 基于Vue+springboot+websocket实现的简短仿微信web聊天室(私聊和群聊功能)(可在线预览)

    写目录 一.界面展示 二.介绍 一.界面展示 之前闲着有空就给自己的个人博客搭了一些附加功能,聊天室也是其中之一,简单的实现了私聊.群聊功能,可以发送emoji表情和图片等,项目已经部署在www.tc ...

  4. vue+websokect实现实时聊天,可单聊、可群聊(一)

    效果图 效果网站链接,安全性不符合实际上线使用,仅供学习交流 https://livequeen.top 效果小程序二维码 (需现在web端获取账号)          思路 一个实时聊天功能 第一, ...

  5. 【uni-app】小程序实现微信在线聊天(私聊/群聊)

    之前学习使用uni-app简单实现一个在线聊天的功能,今天记录一下项目核心功能的实现过程.页面UI以及功能逻辑全部来源于微信,即时聊天业务的实现使用socket.io,前端使用uni-app开发,后端 ...

  6. uni-app 190扫一扫加入群聊功能(二)

    /pages/chat/scan-add/scan-add.nvue <template><view class="page"><!-- 导航栏 -- ...

  7. uni-app 170邀请加入群聊(二)

    下图是我测试截图 app/controller/group.js 'use strict';const Controller = require('egg').Controller;class Gro ...

  8. react仿微信聊天室|react即时聊天IM系统|react群聊

    react+redux仿微信聊天IM实战|react仿微信界面|react多人群聊天室 最近一直捣鼓react开发,就运用react开发了个仿微信聊天室reactChatRoom项目,基于react+ ...

  9. Go实现简易聊天室(群聊)

    参考:Go 群聊 ( goroutine ) · 语雀 基于websocket的聊天室,可进一步参考: (1) go实现聊天室(WebSocket方式) (2) Golang代码搜集-基于websoc ...

  10. websocket 群聊和单聊实现简单在线客服

    根据菜鸟教程上的解释: WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据.在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间 ...

最新文章

  1. 未来15年,人工智能将带给城市8种改变
  2. [BUUCTF-pwn]——hitcontraining_uaf
  3. android组件的下拉回弹,转:Android可以下拉/上拉回弹的ListView原理
  4. Excel曲线拟合的精度问题
  5. creator小功能----浅谈cc.Director与 资源加载策略
  6. JAVA解析xml文件(DOM)
  7. php数据库太小要怎么改,PHP入坑之 MySqli对数据库增删改查
  8. 群晖6.1安装php3.6_教程分享 --- jun大神 VMWare虚拟机安装黑群晖 (DSM6.1)
  9. JUCE框架教程(5)——Plugin项目构造基础
  10. 识别到硬盘 计算机不显示盘符,Win10系统下移动硬盘可以识别但是不显示盘符的解决方法...
  11. unity reflect_使用Unity Reflect的不同方法
  12. 如何做好网站的安全性测试
  13. BTC地址不同格式的区别
  14. 非线性控制2.0——模糊逼近
  15. BugMeNot:查找和共享登录名(一个神奇的网站)
  16. Matplotlib——散点图_多种自定义
  17. k8s资源之service
  18. 视频流快速处理技术之二——基于数据量波动特性的视频静止画面检测
  19. python人工智能项目实战 桑塔努·帕塔纳亚克 pdf_(特价书)Python人工智能项目实战...
  20. 第9章第29节:完成团队介绍幻灯片的制作 [PowerPoint精美幻灯片实战教程]

热门文章

  1. EF-EntityFrameWork中文名:实体框架(数据持久化框架)
  2. 深入解析内存原理:DRAM的基本原理
  3. c语言 随机四则运算,随机四则运算 C语言
  4. 计算机应用基础个人简历制作,计算机应用基础信息技术基础《项目3-4制作个人简历》教案...
  5. 证书与签名(一):数字签名是什么
  6. android输入法剪贴板,QQ输入法手安卓V5.4剪贴板 任性粘贴
  7. 基于嵌入式端的人脸识别算法
  8. iphone个系列尺寸_iPhone9只是套模iPhone8,这些才是iPhone经典款,你用过哪些?
  9. php静态登录界面网页代码,css+html如何仿花瓣网实现静态登陆页面?(代码实例)...
  10. 什么是物联网应用开发(IoT Studio)