当前位置: 首页 > news >正文

websocket和SSE通信示例(无需安装任何插件)

websocket和SSE通信示例(无需安装任何插件)

源码示例(两种方案任意切换)

data(){return {heartBeatInterval:5000,// 心跳间隔时间,单位为毫秒webSocket:null,heartBeatTimer:null,}
},
mounted() {// this.initWebSocket();//方案1,全双工通信websocket,部署线上后要使用wss,要求线上是域名且为httpsthis.createSseConnect();//方案2,sse,单工通信(http长连接)},methods:{// sse建立连接createSseConnect(){let self = this;if(window.EventSource){const eventSource = new EventSource(`${this.$sseUrl}/sse/createConnect?clientId=${this.$store.state.user.name}`);eventSource.onmessage = (e) =>{console.log("msg info:", e.data);self.handleMessage(JSON.parse(e.data))};eventSource.onopen = (e) =>{console.log("已建立连接~")};eventSource.onerror = (e) =>{if (e.readyState == EventSource.CLOSED) {console.log("连接关闭");} else if (eventSource.readyState == EventSource.CONNECTING) {console.log("正在重连");} else {console.log('error', e);}};eventSource.close = (e) =>{console.log("连接关闭");};}else{console.log("你的浏览器不支持消息通信~")}console.log(" 测试 打印")},handleMessage(data) {this.msgContent = data.messageTitle;this.messageId = data.messageId;this.newMsgCount = data.newInfoCount;if(this.msgContent){this.showMessagePop = true;}},initWebSocket() {this.webSocket = new WebSocket(`${this.$websocketUrl}/websocket/${this.$store.state.user.name}`);this.webSocket.onopen = () => {// 建立连接后开始发送心跳包this.startHeartBeat();};this.webSocket.onmessage = (event) => {// 处理服务器发送的消息this.handleMessage(JSON.parse(event.data))};this.webSocket.onclose = () => {console.log('WebSocket连接已关闭');// 连接关闭后停止心跳包this.stopHeartBeat();   // 可根据需要重新连接// reconnect();};},startHeartBeat() {// 每隔一段时间发送心跳包this.heartBeatTimer = setInterval(() => {if (this.webSocket.readyState === this.webSocket.OPEN) {this.webSocket.send('hello,这是一个心跳包'); // 发送心跳包}}, this.heartBeatInterval);},stopHeartBeat() {// 停止心跳包发送clearInterval(this.heartBeatTimer);},}

注意事项

使用websocket要注意

  1. websocket一段时间后会自动关闭链接,所以要定时发送心跳包请求检测心跳以保证链接持续有效
  2. 在vue项目中配置代理时要注意target地址是ws协议的target: 'ws://x.x.x.x:8080',
  3. websocket打包部署线上必须走wss,这就要求线上域名为https请求

使用SSE要注意

1.当确认请求地址无误,postman也可以请求通,但是唯独在项目中请求一直pending时,前端可以在devServer中配置compress:false,参数来解决。
2.当本地请求正常,部署到线上之后就一直请求超时,statuscode栏显示已屏蔽mixed-content,让后端在nginx配置中加上buffer相关的配置即可

http://www.lryc.cn/news/259797.html

相关文章:

  • 计算机网络(三)
  • HttpURLConnection OOM问题记录
  • WT588F02B单片机语音芯片在磁疗仪中的应用介绍
  • 深度学习——第5章 神经网络基础知识
  • 微信网页授权步骤说明
  • linux bash shell变量操作符 —— 筑梦之路
  • 2.61【Python生成器与迭代器】
  • devecho stuido npm 失败
  • postgreSql逻辑复制常用语句汇总和说明
  • 设置Ubuntu或树莓派系统,允许root用户ssh方式连接
  • Ubuntu安装向日葵【远程控制】
  • jquery 实现倒计时60秒
  • 单例模式:饿汉模式、懒汉模式
  • 提升方法AdaBoost
  • Python自动化测试系列[v1.0.0][多种数据驱动实现附源码]
  • 【论文笔记】Gemini: A Family of Highly Capable Multimodal Models——细看Gemini
  • iOS加密CoreML模型
  • Springboot自定义start首发预告
  • [GWCTF 2019]我有一个数据库1
  • 【LeetCode每日一题】1904. 你完成的完整对局数
  • +0和不+0的性能差异
  • 美颜技术讲解:视频美颜SDK的开发与集成
  • 期末数组函数加强练习
  • 如何下载B站视频?我来教你B站视频下载方法
  • AcWing 3709:单链表节点交换 ← 四川大学考研机试题
  • RocketMQ源码 Broker-ConsumerFilterManager 消费者数据过滤管理组件源码分析
  • 数据挖掘-07-航空公司客户价值分析(包括数据和代码)
  • 浏览器 css 默认的字体图表
  • JAVA:注册表窗口的实现
  • Liunx Centos 防火墙操作