WebSocket服务端数据推送及心跳机制(Spring Boot + VUE)

一、WebSocket简介

HTML5规范在传统的web交互基础上为我们带来了众多的新特性,随着web技术被广泛用于web APP的开发,这些新特性得以推广和使用,而websocket作为一种新的web通信技术具有巨大意义。WebSocket是HTML5新增的协议,它的目的是在浏览器和服务器之间建立一个不受限的双向通信的通道,比如说,服务器可以在任意时刻发送消息给浏览器。支持双向通信。

二、WebSocket通信原理及机制

websocket是基于浏览器端的web技术,那么它的通信肯定少不了http,websocket本身虽然也是一种新的应用层协议,但是它也不能够脱离http而单独存在。具体来讲,我们在客户端构建一个websocket实例,并且为它绑定一个需要连接到的服务器地址,当客户端连接服务端的时候,会向服务端发送一个消息报文

三、WebSocket特点和优点

1、支持双向通信,实时性更强。
2、更好的二进制支持。
3、较少的控制开销。连接创建后,ws客户端、服务端进行数据交换时,协议控制的数据包头部较小。在不包含头部的情况下,服务端到客户端的包头只有2~10字节(取决于数据包长度),客户端到服务端的的话,需要加上额外的4字节的掩码。而HTTP协议每次通信都需要携带完整的头部。
4、支持扩展。ws协议定义了扩展,用户可以扩展协议,或者实现自定义的子协议。(比如支持自定义压缩算法等)
5、建立在tcp协议之上,服务端实现比较容易
6、数据格式比较轻量,性能开销小,通信效率高
7、和http协议有着良好的兼容性,默认端口是80和443,并且握手阶段采用HTTP协议,因此握手的时候不容易屏蔽,能通过各种的HTTP代理

四、WebSocket心跳机制

在使用websocket过程中,可能会出现网络断开的情况,比如信号不好,或者网络临时性关闭,这时候websocket的连接已经断开,而浏览器不会执行websocket 的 onclose方法,我们无法知道是否断开连接,也就无法进行重连操作。如果当前发送websocket数据到后端,一旦请求超时,onclose便会执行,这时候便可进行绑定好的重连操作。

       心跳机制是每隔一段时间会向服务器发送一个数据包,告诉服务器自己还活着,同时客户端会确认服务器端是否还活着,如果还活着的话,就会回传一个数据包给客户端来确定服务器端也还活着,否则的话,有可能是网络断开连接了。需要重连~
 

五、在后端Spring Boot 和前端VUE中如何建立通信

1、在Spring Boot 中 pom.xml中添加 websocket依赖

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

2、创建 WebSocketConfig.java 开启websocket支持

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;/*** 开启WebSocket支持* */
@Configuration
public class WebSocketConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}}

3、创建 WebSocketServer.java 链接

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;@ServerEndpoint("/websocket/testsocket")
@Component
public class WebSocketServer {private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。private static int onlineCount = 0;//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();//与某个客户端的连接会话,需要通过它来给客户端发送数据private Session session;/*** 连接建立成功调用的方法*/@OnOpenpublic void onOpen(Session session) {this.session = session;webSocketSet.add(this);     //加入set中addOnlineCount();           //在线数加1log.info("有新窗口开始监听,当前在线人数为" + getOnlineCount());try {sendMessage("连接成功");} catch (Exception e) {log.error("websocket IO异常");}}/*** 连接关闭调用的方法*/@OnClosepublic void onClose(Session session) {try {webSocketSet.remove(this);  //从set中删除subOnlineCount();           //在线数减1session.close();log.info("有一连接关闭!当前在线人数为" + getOnlineCount());} catch (IOException e) {e.printStackTrace();}}/*** 收到客户端消息后调用的方法** @param message 客户端发送过来的消息*/@OnMessagepublic void onMessage(String message, Session session) {log.info("收到的信息:"+message);Map<String, Object> maps = new HashMap<>();maps.put("type", message);this.sendInfo(maps);}/**** @param session* @param error*/@OnErrorpublic void onError(Session session, Throwable error) {log.error("发生错误");error.printStackTrace();}/*** 实现服务器主动推送*/public void sendMessage(Object obj)  {try {synchronized (this.session) {this.session.getBasicRemote().sendText((JSON.toJSONString(obj)));}} catch (Exception e) {e.printStackTrace();}}/*** 群发自定义消息* */public static void sendInfo(Object obj) {for (WebSocketServer item : webSocketSet) {try {item.sendMessage(obj);} catch (Exception e) {continue;}}}public static synchronized int getOnlineCount() {return onlineCount;}public static synchronized void addOnlineCount() {WebSocketServer.onlineCount++;}public static synchronized void subOnlineCount() {WebSocketServer.onlineCount--;}
}

4、创建一个测试调用websocket发送消息 TimerSocketMessage.java (用定时器发送推送消息

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;import java.util.HashMap;
import java.util.Map;@Component
@EnableScheduling
public class TimerSocketMessage {/*** 推送消息到前台*/@Scheduled(cron = "*/5 * * * * * ")public void SocketMessage(){SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Map<String, Object> maps = new HashMap<>();maps.put("type", "sendMessage");maps.put("data", sdf.format(new Date()));WebSocketServer.sendInfo(maps);}
}

5、在VUE中创建和后端 websocket服务的连接并建立心跳机制。

<template><div><el-row :gutter="$ui.layout.gutter.g10"><el-col :span="$ui.layout.span.one" style="background-color: #FFFFFF; padding: 10px;"><el-form ref="form" :model="form" label-width="80px" size="small" :inline="true"><el-form-item label="生成数量"><el-input-number v-model="form.number" :min="1" :max="999" label="描述文字" /></el-form-item><el-form-item label="数值范围"><el-input-number v-model="form.start" :min="1" :max="9999999999" label="描述文字" /> ~<el-input-number v-model="form.end" :min="1" :max="9999999999" label="描述文字" /></el-form-item><el-form-item><el-button size="mini" type="primary" @click="spawn">生成</el-button></el-form-item></el-form></el-col></el-row><h1> websocket 消息推送测试:{{data}}</h1></div>
</template><script>
export default {name: 'Index',data() {return {form: {number: 1,start: 1,end: 100},data:0,timeout: 28 * 1000,//30秒一次心跳timeoutObj: null,//心跳心跳倒计时serverTimeoutObj: null,//心跳倒计时timeoutnum: null,//断开 重连倒计时websocket: null,}},created () {// 初始化websocketthis.initWebSocket()},methods: {spawn() {},initWebSocket () {let url = 'ws://localhost:8086/demo/websocket/testsocket'this.websocket = new WebSocket(url)// 连接错误this.websocket.onerror = this.setErrorMessage// 连接成功this.websocket.onopen = this.setOnopenMessage// 收到消息的回调this.websocket.onmessage = this.setOnmessageMessage// 连接关闭的回调this.websocket.onclose = this.setOncloseMessage// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。window.onbeforeunload = this.onbeforeunload},reconnect () { // 重新连接if(this.lockReconnect) return;this.lockReconnect = true;//没连接上会一直重连,设置延迟避免请求过多this.timeoutnum && clearTimeout(this.timeoutnum);this.timeoutnum = setTimeout(() => {//新连接this.initWebSocket();this.lockReconnect = false;}, 5000);},reset () { // 重置心跳// 清除时间clearTimeout(this.timeoutObj);clearTimeout(this.serverTimeoutObj);// 重启心跳this.start();},start () { // 开启心跳this.timeoutObj && clearTimeout(this.timeoutObj);this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);this.timeoutObj = setTimeout(() => {// 这里发送一个心跳,后端收到后,返回一个心跳消息,if (this.websocket && this.websocket.readyState == 1) { // 如果连接正常this.websocketsend('heartbeat');} else { // 否则重连this.reconnect();}this.serverTimeoutObj = setTimeout(() => {//超时关闭this.websocket.close();}, this.timeout);}, this.timeout)},setOnmessageMessage (event) {let obj = JSON.parse(event.data);console.log("obj",obj)switch(obj.type) {case 'heartbeat'://收到服务器信息,心跳重置this.reset();break;case 'sendMessage':this.data = obj.dataconsole.log("接收到的服务器消息:",obj.data)}},setErrorMessage () {//重连this.reconnect();console.log("WebSocket连接发生错误" + '   状态码:' + this.websocket.readyState)},setOnopenMessage () {//开启心跳this.start();console.log("WebSocket连接成功" + '   状态码:' + this.websocket.readyState)},setOncloseMessage () {//重连this.reconnect();console.log( "WebSocket连接关闭" + '   状态码:' + this.websocket.readyState)},onbeforeunload () {this.closeWebSocket();},//websocket发送消息websocketsend(messsage) {this.websocket.send(messsage)},closeWebSocket() { // 关闭websocketthis.websocket.close()},}
}
</script>

6、启动项目开始测试结果

 7、vue文件连接websocket的url地址要拼接 context-path: /demo

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/76429.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

适合程序员的DB性能测试工具 JMeter

背景 1、想要一款既要能压数到mysql&#xff0c;又要能压数到postGre&#xff0c;还要能压数到oracle的自动化工具 2、能够很容易编写insert sql&#xff08;因为需要指定表和指定字段类型压数据&#xff09;&#xff0c;然后点击运行按钮后&#xff0c;就能直接运行&#xff…

Java请求Http接口-hutool的HttpUtil(超详细-附带工具类)

概述 HttpUtil是应对简单场景下Http请求的工具类封装&#xff0c;此工具封装了HttpRequest对象常用操作&#xff0c;可以保证在一个方法之内完成Http请求。 此模块基于JDK的HttpUrlConnection封装完成&#xff0c;完整支持https、代理和文件上传。 导包 <dependency>&…

MongoDB 安装 linux

本文介绍一下MongoDB的安装教程。 系统环境&#xff1a;CentOS7.4 可以用 cat /etc/redhat-release 查看本机的系统版本号 一、MongoDB版本选择 当前最新的版本为7.0&#xff0c;但是由于7.0版本安装需要升级glibc2.25以上,所以这里我暂时不安装该版本。我们选择的是6.0.9版本…

服务器感染了.360勒索病毒,如何确保数据文件完整恢复?

引言&#xff1a; 随着科技的不断进步&#xff0c;互联网的普及以及数字化生活的发展&#xff0c;网络安全问题也逐渐成为一个全球性的难题。其中&#xff0c;勒索病毒作为一种危害性极高的恶意软件&#xff0c;在近年来频频袭扰用户。本文91数据恢复将重点介绍 360 勒索病毒&a…

HBuilderX获取iOS证书的打包步骤

简介&#xff1a; 目前app开发&#xff0c;很多企业都用H5框架来开发&#xff0c;而uniapp又是这些h5框架里面最成熟的&#xff0c;因此hbuilderx就成为了开发者的首选。然而,打包APP是需要证书的&#xff0c;那么这个证书又是如何获得呢&#xff1f; 生成苹果证书相对复杂一些…

JVM - 垃圾收集器

目录 垃圾收集器 串行垃圾收集器 并行垃圾收集器 什么是 吞吐量优先 什么是 响应时间优先 &#xff1f; CMS&#xff08;并发&#xff09;垃圾收集器 G1 垃圾收集器 垃圾收集器 垃圾收集器大概可以分为&#xff1a; 串行垃圾收集器并行垃圾收集器CMS&#xff08;并发&a…

springBoot 配置文件 spring.mvc.throw-exception-if-no-handler-found 参数的作用

在Spring Boot应用中&#xff0c;可以通过配置文件来控制当找不到请求处理器&#xff08;handler&#xff09;时是否抛出异常。具体的配置参数是spring.mvc.throw-exception-if-no-handler-found。 默认情况下&#xff0c;该参数的值为false&#xff0c;即当找不到请求处理器时…

企业百家号蓝V认证后,百度营销基木鱼落地页如何嵌入百家号中

首先搭建百度营销基木鱼落地页 在我们的百度营销后台&#xff0c;点击基木鱼跳转至百度营销基木鱼页面&#xff0c;在我的站点位置&#xff0c;可以创建H5站点&#xff0c;PC站点等&#xff0c;创建完成后可以点击复制基木鱼落地页的链接。 注意事项 1、企业百家号需要进行…

【React学习】React组件生命周期

1. 介绍 在 React 中&#xff0c;组件的生命周期是指组件从被创建到被销毁的整个过程。React框架提供了一系列生命周期方法&#xff0c;在不同的生命周期方法中&#xff0c;开发人员可以执行不同的操作&#xff0c;例如初始化状态、数据加载、渲染、更新等。一个组件的生命周期…

dirsearch目录扫描工具的使用

文章目录 工具下载及环境准备查看帮助信息进行目录扫描 官方介绍 &#xff1a;An advanced command-line tool designed to brute force directories and files in webservers, AKA web path scanner 一个高级命令行工具&#xff0c;用于暴力破解网络服务器中的目录和文件&…

Servlet+Jsp+JDBC实现房屋租赁管理系统(源码+数据库+论文+系统详细配置指导+ppt)

一、项目简介 本项目是一套基于ServletJsp房屋租赁管理系统&#xff0c;主要针对计算机相关专业的正在做毕设的学生与需要项目实战练习的Java学习者。 包含&#xff1a;项目源码、数据库脚本等&#xff0c;该项目附带全部源码可作为毕设使用。 项目都经过严格调试&#xff0c;…

优化GitHub网站访问慢的问题

方法一、修改host文件解决 大型网站服务器都不会是只有一台服务器,而是多台服务器组成的集群一起对外提供服务。 使用站长工具测速&#xff0c;找一个速度比较快的服务器。 图中可以看到140.82.121.4这个ip比较快&#xff0c; 下面修改hosts: Mac 在 /etc/hosts 中&#x…