背景:公司业务需求,在官网上面需添加客服答疑页面,一般都是使用websocket通信,主要是它是一个低延迟、全双工、跨域通信通道。

注:页面底部有效果图

一、简单介绍

sockjs-client
sockjs-client是从SockJS中分离出来的用于客户端使用的通信模块,是一个浏览器的JavaScript库。主要是为了浏览器的兼容性,有些浏览器是不支持websocket,Spring框架提供了基于SockJS协议的透明的回退选项,也就是说一旦不支持这种模式,SockJS会自动降为轮询的方式。

stomjs
STOMP(Simple Text-Orientated Messaging Protocol) 面向消息的简单文本协议;
WebSocket是一个消息架构,不强制使用任何特定的消息协议,它依赖于应用层解释消息的含义。
与HTTP不同,WebSocket是处在TCP上非常薄的一层,会将字节流转化为文本/二进制消息,因此,对于实际应用来说,WebSocket的通信形式层级过低,因此,可以在 WebSocket 之上使用STOMP协议,来为浏览器和server间的 通信增加适当的消息语义。

STOMP与WebSocket 的关系:

HTTP协议解决了web浏览器发起请求以及web服务器响应请求的细节,假设HTTP协议不存在,只能使用TCP套接字来编写web应用,你可能认为这是一件疯狂的事情;
直接使用WebSocket(SockJS)就很类似于使用TCP套接字来编写web应用,因为没有高层协议,就需要我们定义应用间发送消息的语义,还需要确保连接的两端都能遵循这些语义;
同HTTP在TCP套接字上添加请求-响应模型层一样,STOMP在WebSocket之上提供了一个基于帧的线路格式层,用来定义消息语义。

二、安装插件

npm install sockjs-client
npm install stompjs

三、页面代码

html代码

      <!-- 聊天弹框 主要是客户聊天的页面代码 --><el-dialogref="chatDialog":visible.sync="chatDialog"width="360px"class="chatDialog":close-on-click-modal="false":close="chatClose"title="国瑞在线"><div ref="chatContentRef" :contenteditable="false" class="chatContent clearfix" /><div class="chating"><a href="javascript:void(0)" class="emtionImg" :contenteditable="false" @click="emtionShow()"><img src="@/assets/images/index/icon_index_service_emtion.png" alt=""></a><emotion v-if="emtionIsShow" class="emotion" :height="138" @emotion="handleEmotion" /><el-uploadclass="upload"action="https://jsonplaceholder.typicode.com/posts/"auto-uploadmultiple:before-upload="beforeUpload"><img src="@/assets/images/index/icon_index_service_img.png" alt=""></el-upload><divref="textarea"class="textarea":contenteditable="contenteditable"@keyup.enter="sendMessage()"@keydown.enter.prevent@blur="focusContent"v-html="content"/><div class="chatBtn"><el-button class="chatBtn_1" @click="closeChatDialog()">结束会话</el-button><el-button class="chatBtn_2" @click="sendMessage()">发送</el-button></div></div><img src="@/assets/images/index/icon_index_service_logo.png" alt=""></el-dialog><!-- 图片弹框 --><el-dialogref="previewDialog":visible.sync="previewDialog":width="imgWidth"><img :src="imgSrc" alt=""></el-dialog><!-- 结束会话弹框 --><el-dialog:visible.sync="closeChatCheckDialog"width="240px"class="closeChatCheck"><span>是否结束当前会话</span><span slot="footer" class="dialog-footer"><el-button type="primary" @click="closeChatCheck()">是</el-button><el-button @click="closeChatCheckDialog = false">否</el-button></span></el-dialog>

JS代码

import Emotion from '../../../components/Emotion/index'; //表情包的使用
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
export default {data(){return {stompClient:'',timer:'',}},methods:{init() {if (typeof (WebSocket) === 'undefined') {alert('您的浏览器不支持socket');} else {this.connection();}},  connection() {// 建立连接对象let socket = new SockJS('http://192.168.1.102:9632/web-websocket/webSocketServer');// 获取STOMP子协议的客户端对象this.stompClient = Stomp.over(socket);// 向服务器发起websocket连接const userId = Number(Math.random().toString().substr(3, 8) + Number(Date.now().toString().substr(3, 8))).toString(36);this.user = {   //随机生成用户IDusername: userId};this.stompClient.connect(this.user,() => {this.stompClient.subscribe('/user/' + userId + '/queue/getResponse', (response) => { // 订阅服务端提供的某个topicif (JSON.parse(response.body) && JSON.parse(response.body).type === 'NOTICE' && JSON.parse(response.body).status === 2) {this.users = JSON.parse(response.body).userName;this.contenteditable = true;const noticeMsg = `<div style="margin-top: 20px;text-align:center;margin-bottom: 10px;">您已成功连接</div>`;this.$refs.chatContentRef.innerHTML += noticeMsg;} else if (JSON.parse(response.body) && JSON.parse(response.body).type === 'NOTICE' && JSON.parse(response.body).status === 1) {const noticeMsg = `<div style="margin-top: 20px;text-align:center;margin-bottom: 10px;">当前连接人数较多,请耐心稍等</div>`;this.$refs.chatContentRef.innerHTML += noticeMsg;this.contenteditable = false;}if (JSON.parse(response.body).text) {this.$refs.chatContentRef.innerHTML +=`<div class="clearfix"><div style="float:left"> <span style="margin-right:8px;">卑微客服在线答疑 ${this.$verify.NowDate3()}</span></div> </div><div class="clearfix"><div style="background-color:#FFFFFF;color:black;padding:8px 8px;text-align:rigth;margin-top:8px;border-radius:6px;float:left"> ${JSON.parse(response.body).text}</div></div><br />`;this.$refs.chatContentRef.scrollTop = this.$refs.chatContentRef.scrollHeight;}console.log(response, '订阅成功'); // msg.body存放的是服务端发送给我们的信息});}, (err) => {// 连接发生错误时的处理函数console.log('失败',err);});},    disconnect() {// 断开连接if (this.stompClient) {this.stompClient.disconnect();}},sendMessage() {  //发送消息const text = this.$refs.textarea.innerHTML;var msg = {'text': this.$refs.textarea.innerHTML,'userName': this.users};this.stompClient.send('/sendUser', {}, JSON.stringify(msg)); //发送消息的主要代码if (text === '') {return;}const chatContentRef = this.$refs.chatContentRef;const time = this.$verify.NowDate3();chatContentRef.innerHTML +=`<div class="clearfix"><div style="float:right"> <span style="margin-right:8px;">我</span>${time}</div> </div><div class="clearfix"><div style="background-color:#5595FF;color:#fff;padding:8px 8px;text-align:rigth;margin-top:8px;margin-left:52px;border-radius:6px;float:right">${text} </div></div><br />`;chatContentRef.scrollTop = chatContentRef.scrollHeight;this.$refs.textarea.innerHTML = '';this.content = '';},closeChatDialog() {this.closeChatCheckDialog = true;},chatClose() {this.$refs.chatContentRef.innerHTML = '';},emtionShow() {const that = this;that.emtionIsShow = !that.emtionIsShow;this.$refs.textarea.focus();},handleEmotion(i) {this.lastEditRange.deleteContents(); // 删除文档的区域var el = document.createElement('div');el.innerHTML = this.emotion(i);var frag = document.createDocumentFragment(); // 创建一个虚拟的domvar node;var lastNode;while ((node = el.firstChild)) {lastNode = frag.appendChild(node);}this.lastEditRange.insertNode(frag);// Preserve the selectionif (lastNode) {this.lastEditRange = this.lastEditRange.cloneRange();this.lastEditRange.setStartAfter(lastNode);this.lastEditRange.collapse(true);this.selection.removeAllRanges();this.selection.addRange(this.lastEditRange);}},// 将匹配结果替换表情图片emotion(res) {const word = res.replace(/\#|\;/gi, '');return `<img style="width:20px;" src="https://twemoji.maxcdn.com/v/12.1.4/72x72/${word}.png" align="middle">`;},focusContent() {this.selection = window.getSelection();this.lastEditRange = this.selection.getRangeAt(0);},beforeUpload(val) {const file = val;const reader = new FileReader();reader.readAsDataURL(file);const chatContentRef = this.$refs.chatContentRef;const time = this.$verify.NowDate3();const stompClient = this.stompClient;const users = this.users;reader.onload = function() {chatContentRef.innerHTML +=`<div class="clearfix"><div style="float:right"> <span style="margin-right:8px;">我</span>${time}</div> </div><div class="clearfix"><div style="background-color:#5595FF;color:#fff;padding:8px 8px;text-align:rigth;margin-top:8px;margin-left:52px;border-radius:6px;float:right"> <img src=${reader.result} style="max-width:100px;"></img> </div></div><br />`;const innerHTML = ` <img src=${reader.result} style="max-width:100px;"></img>`;var msg = {'text': innerHTML,'userName': users};stompClient.send('/sendUser', {}, JSON.stringify(msg));};},closeChatCheck() { //断开链接this.chatDialog = false;this.closeChatCheckDialog = false;this.disconnect();}},mounted(){this.init();}
}

以上就是websocket的通信内容。。。

······························································我是一条分割线····························································
以下是页面效果图:
1.客服页面:

2.客户页面:

vue项目使用SockJS插件实现webSocket通信相关推荐

  1. VsCode工具开发vue项目必装插件

    VsCode工具开发vue项目必装插件 目录 VsCode工具开发vue项目必装插件 1.概述 2.VsCode插件清单 2.1.Vetur插件让vue文件代码高亮 2.2.Vue VSCode Sn ...

  2. 在 Microsoft Edge 浏览器上安装 Vue 项目调试扩展插件 Vue-Devtools

    在 Microsoft Edge 浏览器上安装 Vue 项目调试扩展插件 Vue-Devtools Vue-Devtools 插件是一个 Vue 项目的调试插件 Microsoft Edge 浏览器是 ...

  3. vue项目防抖节流插件的使用

    vue项目防抖节流插件的使用 lodash 安装 npm i --save lodash 在main.js引入 import _ from 'lodash' 使用: //防抖 //参数写在functi ...

  4. 前端压缩图片 -- vue项目使用localResizeIMG插件 -- 实例

    前端压缩图片 -- vue项目使用localResizeIMG插件 -- 实例 本博没有新的东西, 都是东拼西凑的. 但是, 组合出了个宝贝, 包括: 文件类型/宽高/大小的校验, 还有展示图片 参照 ...

  5. vue项目 报sockjs.js?9be2:1606 GET http://192.168.43.226:8080/sockjs-node/info?t=1584966826465 net::ERR_

    在做vue项目时,突然就报sockjs.js?9be2:1606 GET http://192.168.43.226:8080/sockjs-node/info?t=1584966826465 net ...

  6. vue项目vscode常用插件

    对于很多使用vscode编写vue项目的新手同学来说,可能不知道使用什么插件,这里简单说一下我常用的几款插件. 1. vetur vetur能够实现在 .vue 文件中: 语法错误检查,包括 CSS/ ...

  7. 使用H5Stream实现rtsp视频流播放,在Vue项目中 (无插件、可多视频源播放、亲测可用)

    本文主要介绍用H5Stream 在Web页面播放摄像头的RTSP视频流,从0到1的过程.包括WebSocket代理.h5ss.bat文件 运行一会就自己卡死了.H5ss服务死掉自动定时重启的脚本 等可 ...

  8. 环信是否支持html,VUE项目集成环信WebIM即时通信以及所遇到的问题

    功能背景: 以前和朋友一块儿作了一个wbe项目集成环信的即时通讯的功能,作的时候感叹web端文档太少,并且npm包有一些坑,记录下来写了这篇博客,以后不断有人加我微信问我,怎么集成.如今我再来重写一下 ...

  9. vue项目中引入插件

    (一)Vue引入jquer以及jquery插件步骤 (一)在package.json中添加 (二)安装jquery npm install jquery (三)修改build/webpack.base ...

  10. vue编译速度过慢?大型vue 项目使用dll插件优化编译速度,效果显著

    为什么要优化编译速度 vue项目过大,引用的组件过多,当启动项目打包项目或者修改代码的时候会发现编译速度太慢,浪费时间,甚至每改一行代码都可能需要编译三十秒以上,所以必须要优化,这样是在浪费生命 如何 ...

最新文章

  1. P5568 [SDOI2008]校门外的区间(离散数学应用+线段树+开闭区间处理)(校门三部曲)难度⭐⭐⭐⭐
  2. php goto call,Php中的goto用法
  3. Oracle按照时间统计总结
  4. JAVA 条件语句 跟PHP没有区别!!!!!
  5. 关于精密空调,你需要了解的都在这里!
  6. 直接拿来用!最火的Android开源项目(完结篇)(转)
  7. Otsu algorithm
  8. tomcat mysql如何优化_Tomcat+Mysql高并发配置优化讲解
  9. golang 日志分析_容器日志采集利器:Filebeat深度剖析与实践
  10. java timetasker_Java网络与多线程系列之1:实现一个简单的对象池
  11. PixelFormat 枚举
  12. 校园导游图的课程设计(三)
  13. 关于学习BEX5的问题
  14. 车牌识别SDK原理分析
  15. NLP+词法系列(一)︱中文分词技术小结、几大分词引擎的介绍与比较
  16. 【BUUCTF】[WUSTCTF2020]alison_likes_jojo
  17. jetbrains(IDEA/PyCharm)官网地址打不开
  18. springboot中报415错误怎么解决?
  19. 前端培训教程JavaScript
  20. php 索引数组应用实例,php数字索引数组实例用法总结

热门文章

  1. 禅道和JIRA大对比
  2. 图像处理--VGA分辨率
  3. Intellij idea破解2017
  4. 打开其他软件时,老是弹出Xftp6安装的问题
  5. 【Godot】Godot 插件制作流程
  6. vue开发app项目实例
  7. 原生列表table固定表头
  8. 如何调整Exadata DB节点文件系统大小
  9. 搜罗到一个简洁、支持免费听和下载全网音乐的网站
  10. Qt开发笔记:OpenSSL库介绍、windows上mingw32版本的OpenSSL编译模块化