本次需求

做一个高仿微信网页版在线聊天系统,好友相互之间进行单聊

技术支持

springboot服务端提供websocket服务端连接

vue-cli提供websocket客户端与后端进行连接

实现效果

实现过程

vue-cli脚手架需要做的工作

首先在data中定义

websock: null,
message: "", //要发送的消息
receiveAccount: "", //接收人的账号
msgList: [], 聊天消息列表展示
currentTab:""  //当前窗口是在和哪个账号聊天 在点击选择好友时触发的方法中要初始化这个变量,把接收者的账号赋值给它

其次在methods中添加方法,以供连接websocket服务端

initWebSocket() {this.websock = null;//判断当前浏览器是否支持WebSocketvar wsUrl = "ws://vue.tiger2.cn:8082/charRoomServer";//带上自己的账号(发送人账号) 参数var allUrl = wsUrl + "/" + window.localStorage.getItem("account");if ("WebSocket" in window) {//初始化weosocket(必须)this.websock = new WebSocket(allUrl); //新建一个webstock对象this.websock.onopen = this.websocketonopen;this.websock.onmessage = this.websocketonmessage;this.websock.onerror = this.websocketonerror;this.websock.onclose = this.websocketclose;} else {alert("当前浏览器 Not support websocket");}},websocketonopen() {console.log("---连接建立成功---");//websocket连接后发送数据(send发送)//第一次建立成功之后发送接收人账号,在后端接收并存储let actions = this.receiveAccount; this.websocketsend(actions);},websocketonerror() {//连接建立失败重连this.initWebSocket();},websocketonmessage(e) {//数据接收console.log("-----websocket接收到的发送的数据-----");let str = e.data;let index = str.lastIndexOf(":");let sendUserAccount = str.substring(0, index);let sendMessage = str.substring(index + 1, str.length);console.log("发送人:" + sendUserAccount + "----------发送信息:" + sendMessage);let account = window.localStorage.getItem("account");//自己的账号//如果当前聊天的人是消息发送者  或者  发送者是自己//【那么就把消息发送到当前聊天窗口,否则只传到后端存储到数据库中,给好友未读提示即可,不可以发送到当前聊天窗口】if(this.currentTab==sendUserAccount||account==sendUserAccount){if (account == sendUserAccount) {//发送人是自己this.msgList.push({type: true,   //type:true或者false  标记消息是我发送的还是对方发送的,我发送的消息右边排队,对方发送的则左边排队time: new Date(),content: sendMessage});} else {//发送人是对方this.msgList.push({type: false,time: new Date(),content: sendMessage});}}},websocketsend(Data) {//数据发送this.websock.send(Data);},websocketclose(e) {//关闭console.log("断开连接", e);},send() {this.websocketsend(this.message);this.message = "";},

发送按钮触发的方法,进行发送消息,并将文本框置空

send() {this.websocketsend(this.message);this.message = "";}

在(选择好友)点击好友列表的触发方法中进行初始化websocket连接,在触发方法中调用连接方法

toChat(e) {this.currentTab=e.account;//当前窗口是在和哪个账号聊天 赋值this.currentChatUser = "正在和" + e.username + "对话中";this.initWebSocket(); //连接websocketthis.receiveAccount = e.account; //接收者账号 好像和currentTab有点像哈  先不管了,都能用
}

springboot服务端需要做的工作

需要保证内置Tomcat版本在8以上!不过多解释!

首先添加websocket依赖

     <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>

添加WebsocketConfig配置类

该配置类的作用

(1)配置了如下的ServerEndpointExporter之后,websocket客户端连接才会认识并连接在后端被@ServerEndpoint注解标注类(也就是websocket服务端)

(2)注入MainMapper,因为被 SpringBoot WebSocket 对每个客户端连接都会创建一个 WebSocketServer(@ServerEndpoint 注解对应的对象,Bean 注入操作会被直接略过,因而手动注入一个全局变量

(3)为什么需要在WebSocketServer中注入Mapper接口?因为要存储聊天记录嘛!

@Configuration
public class WebsocketConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}@Autowiredpublic void setSelectService(MainMapper mainMapper) {ChatServerController.mainMapper = mainMapper;}
}

WebSocketServer服务端

@ServerEndpoint(value = "/charRoomServer/{param}")
@Component
public class ChatServerController {@Autowiredpublic static MainMapper mainMapper;private Session session;//发送人accountprivate String sendUserAccount;private String receiveUserAccount;//是否第一次进入private boolean isFirst=true;//key代表此次客户端的userId,value代表此次连接对象public static final HashMap<String, Object> connectMap=new HashMap<String, Object>();//key是session的id,value是用户accountpublic static final HashMap<String, String> userMap=new HashMap<String, String>();//服务端收到客户端的连接请求,连接成功后会执行此方法@OnOpenpublic void start(@PathParam(value = "param") String param, Session session) {System.out.println("websocket传来的参数(发送人account):"+param);this.session=session;this.sendUserAccount=param; //接收参数connectMap.put(param,this);userMap.put(session.getId(),param);//保存在线的所有用户}//客户端发来的信息,服务端接收@OnMessagepublic void chat(String clientMessage,Session session) {ChatServerController client=null;if(isFirst){//第一次进入,收到接收人accountSystem.out.println("接收人account已保存:"+clientMessage);receiveUserAccount=clientMessage;isFirst=false;}else{System.out.println("### 接收人已被初始化,开始通信,发送消息 ###");//给接收人窗口发送消息client=(ChatServerController)connectMap.get(receiveUserAccount);if(client!=null){try {client.session.getBasicRemote().sendText(sendUserAccount+":"+clientMessage);} catch (IOException e) {System.out.println("### 发送信息异常,发送失败 ###");e.printStackTrace();}}//给发送人窗口发消息client=(ChatServerController)connectMap.get(sendUserAccount);if(client!=null){try {client.session.getBasicRemote().sendText(sendUserAccount+":"+clientMessage);} catch (IOException e) {System.out.println("### 发送信息异常,发送失败 ###");e.printStackTrace();}}//查询所有的聊天记录的总条数,如果>500条,删除所有记录,并开始保存新的记录,这里是为了降低服务器的消耗,没办法,服务器太差劲(太便宜)//保存聊天记录Map map=new HashMap();map.put("id", UUIDutil.getUUID());map.put("message",clientMessage);map.put("status","1");//未读map.put("time",new Date());map.put("senduser",sendUserAccount);map.put("receiveuser",receiveUserAccount);try {mainMapper.insertMessages(map);} catch (Exception e) {System.out.println("### 保存聊天记录异常,服务器错误 ###");e.printStackTrace();}}}//前台js的ws.close事件,会触发后台的标注onClose的方法@OnClosepublic void close() {userMap.remove(session.getId());connectMap.remove(sendUserAccount);}@OnErrorpublic void onError(Session session,Throwable throwable){System.out.println("发生错误!");throwable.printStackTrace();}

核心过程就已经完了,聊天网页模板是直接下载的,可以自行去查找下载。

选择好友并点击之后显示聊天记录的操作以及消息未读提示这里也不详细说明了,很简单!

GitHub项目地址

vue-cli脚手架地址:https://github.com/fantongxue666/vuecli-lifespace.git

springboot后端地址:https://github.com/fantongxue666/vuecli-lifespace-interface.git

如果你觉得不错,就留个Star吧,创作不易,感谢同志们的鼓励和支持!

vue-cli脚手架集成websocket客户端实现高仿微信网页版在线聊天相关推荐

  1. php++仿网页版微信,vue+web端仿微信网页版聊天室功能

    一.项目介绍 基于Vue2.5.6+Vuex+vue-cli+vue-router+vue-gemini-scrollbar+swiper+elementUI等技术混合架构开发的仿微信web端聊天室- ...

  2. vue仿微信网页版|vue+web端聊天室|仿微信客户端vue版

    一.项目介绍 基于Vue2.5.6+Vuex+vue-cli+vue-router+vue-gemini-scrollbar+swiper+elementUI等技术混合架构开发的仿微信web端聊天室- ...

  3. Spring+Netty+Vue 网页版聊天应用,仿微信网页版聊天

    1:前言 最近在学习网络知识,对于java开发来说,Netty是一个非常重要的框架,无论是为了面试还是日常工作中,如RPC框架Dubbo底层其实是用了Netty, 又或者我们的聊天通信功能,都可能有N ...

  4. vue+h5仿微信网页版聊天室vueWebChat项目

    很早之前就有使用html5技术开发过一个web版仿微信.微博聊天,后来想着用vue技术开发一版,后面由于各种事情,一直没能落定.最近有些空闲就使用vue开发了一个vueWechat聊天室IM项目. 基 ...

  5. Flutter高仿微信-项目实践59篇

    Flutter高仿微信(支持Android和IOS系统) Flutter高仿微信主要包含5大模块: 1.Web服务器 2.Flutter客户端 3.Xmpp即时通讯服务器 4.视频通话服务器 5.腾讯 ...

  6. Vue2.x 核心基础(Vue概述,Vue基本使用,@vue/cli脚手架,Element-UI 的基本使用,Vue模板语法)

    1. Vue概述 尤雨溪:Vue.js的创建者 2014年2月,Vue.js正式发布 2015年10月27日,正式发布1.0.0 2016年4月27日,发布2.0的预览版本 Vue:渐进式JavaSc ...

  7. 猿创征文|【Vue五分钟】 Vue Cli脚手架创建一个项目

    目录 前言 一.创建项目的操作步骤 选择路由模式 选择CSS预编译器 选择如何存放配置 自动下载项目所需的包文件 二.启动vue项目 1.项目目录 2.启动项目 3.浏览器打开项目首页界面 三.项目的 ...

  8. 如何查看vue版本号以及vue/cli脚手架版本号

    查看vue版本号 方法一:直接在项目的package.json文件,找到dependencies就能看到了 方法二:输入命令npm ls vue (或者npm list vue) 查看vue/cli脚 ...

  9. 高仿微信 Windows 端

    高仿微信 Windows 端 版本 M.0.0 运行效果图 为什么要开发本项目 基本信息 开发环境 编程语言 技术指南 使用指南 技术内幕 总括 架构模式 需要时才连接 事件驱动模式 对 Java 对 ...

最新文章

  1. windows linux C/C++获取操作系统、CPU、内存信息、硬盘、IP和MAC
  2. java swing刷新_Swing界面刷新问题(转)
  3. hls fifo_HLS优化方法DATAFLOW你用了吗
  4. Help with arrayCollection.additem()
  5. HttpSession详解
  6. 项目管理文档目录结构
  7. 所谓“卡常数”的常数到底指什么?
  8. C++制作“简单”小游戏
  9. c# Monitor
  10. scala时间处理-获取今天日期,昨天日期,本周时间,本月时间,时间戳转换日期,时间比较
  11. STM32常见通信方式(TTL、RS232、RS485、I2C,SPI,CAN)总结
  12. java毕业设计大众点评管理系统Mybatis+系统+数据库+调试部署
  13. 小伙教你用C++编写飞机大战,编程学习,有源代码哦
  14. 数据结构约瑟夫环实验报告
  15. mysql relay log是什么意思_MySQL--binlog和relay log的生成和删除
  16. Python文档算法整理
  17. AMBA总线协议(包含AHB与APB)
  18. java后端实现文件下载
  19. 鸿蒙开发工具DevEco Studio安装指导
  20. 【OS基础】UEFI与 Legacy BIOS两种启动模式详解

热门文章

  1. 申万宏源证券选择青云专注核心业务开发
  2. 戴上 CAP 这顶帽子,我要和面试官扯皮了
  3. 常用的利率定价 - jason的文章
  4. 清华大学陈煜波:数字经济与中国市场的数字化转型(附视频amp;PPT)
  5. 小科普 | BIOS设置选项详细解释②——内存篇
  6. 快餐业的噩梦?机器人一个小时可做150个汉堡 | 深度
  7. tar 分卷压缩和解压命令
  8. Alamofire网络库基础教程:使用 Alamofire 轻松实现 Swift 网络请求
  9. Mybatis之foreach标签
  10. python输入年份打印全年日历_python使用calendar输出指定年份全年日历的方法