目录

一:SpringBoot后端建立WebSocket服务器

二:前端vue页面 使用echarts和WebSocket

三:服务端给客户端推送消息

四:注意


一:SpringBoot后端建立WebSocket服务器

1.SpringBoot使用WebSocket准备

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

2.WebSocketConfig 注入ServerEndpointExporter 交给spring容器管理

@Configuration
public class WebSocketConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}
}

3.创建WebSocketServer实体类 添加 @ServerEndpoint注解 value 即是前端访问的接口

因为使用websocket的目的只是做消息推送,所以使用了set存储客户端的连接。如果是需要将消息推送给指定客户端,建议使用map或redis将客户端和session绑定存储。

我的代码如下

@Slf4j
//@ServerEndpoint("/api/websocket/{user}")   根据自己的需求选择合适的
@ServerEndpoint(value = "/api/websocket")
@Component
public class WebSocketServer {private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();//    private static Map<String , Session> sessionMap = new ConcurrentHashMap<>();private Session session;// 连接建立成功调用的方法@OnOpenpublic void onOpen(Session session) {this.session = session;webSocketSet.add(this);addOnlineCount();try {sendMessage("连接成功");} catch (IOException e) {e.printStackTrace();}}// 此方法是将用户与对应session绑定,用于推送消息给指定用户//    @OnOpen//  public void onOpen(@PathParam("user") String user, Session session) {//      currentUser = user;//      System.out.println("Connected ... " + session.getId());//    }//连接关闭调用的方法@OnClosepublic void onClose() {webSocketSet.remove(this);}//接收客户端消息// @OnMessage// public void onMessage(String message, Session session) {//    log.info(message);// }//@OnErrorpublic void onError(Session session, Throwable error) {log.error("发生错误");error.printStackTrace();}public void sendMessage(String message) throws IOException {this.session.getBasicRemote().sendText(message);}//将消息推送给所有客户端public void sendInfo(String message) throws IOException {log.info(message);for (WebSocketServer item : webSocketSet) {try {item.sendMessage(message);} catch (IOException e) {continue;}}}
}

二:前端vue页面 使用echarts和WebSocket

echarts的使用在此就不再赘述了,不了解的话,可以点击 vue使用echarts

npm install nodejs-websocket 引入webcoket

main.js中引用

import websocket from 'vue-native-websocket';Vue.use(websocket, '', {connectManually: true, // 手动连接format: 'json', // json格式reconnection: true, // 是否自动重连reconnectionAttempts: 5, // 自动重连次数reconnectionDelay: 2000, // 重连间隔时间
});

websocket的使用主要就是初始化一个websocket实例,定义连接路径即请求后端的接口路径,之后就是绑定该websocket的onopen,onerror,onmessage,onsend,onclose方法,知名见意分别是连接成功之后执行的方法(onopen),错误异常时执行(onerror),接收到后端推送的消息时(onmessage),前端向后端发送消息时(onsend),连接关闭时(onclose)。其中onsend,onclose未在代码中使用,其使用方法与其他方法类似,全部代码如下:

<template><div><div id="chart" style="width: 700px; height: 200px;"></div></div>
</template><script>export default{name:"chart",data(){return{scoket:'',yAxis:[],xAxis:[],}},mounted() {this.chart();this.init();},methods:{//初始化websocket实例init: function () {if(typeof(WebSocket) === "undefined"){alert("您的浏览器不支持socket")}else{// 实例化socketthis.socket = new WebSocket("ws://192.168.1.21:8082/api/websocket")// 监听socket连接this.socket.onopen = this.open// 监听socket错误信息this.socket.onerror = this.error// 监听socket消息this.socket.onmessage = this.getMessage}},open: function () {console.log("socket连接成功")},error: function () {console.log("连接错误")},//接收服务器发来的消息getMessage: function (e) {console.log(e.data);this.xAxis = JSON.parse(e.data).xAxis;this.yAxis = JSON.parse(e.data).yAxis;this.chart();},//给服务器发消息的方法send: function () {this.socket.send(this.parms);},close: function () {console.log("socket已经关闭")},chart(){//有的话就获取已有echarts实例的DOM节点。var mychart = this.$echarts.getInstanceByDom(document.getElementById('timechart')); if (mychart == null) { // 如果不存在,就进行初始化。mychart = this.$echarts.init(document.getElementById('chart'));}var option = {title: {text: '时间(ms)/阶段'},tooltip: {trigger: 'axis'},legend: {// data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']},grid: {left: '3%',right: '4%',bottom: '3%',containLabel: true},toolbox: {feature: {saveAsImage: {}}},xAxis: {type: 'category',boundaryGap: false,data: this.xAxis},yAxis: {type: 'value'},series: [{type: 'line',stack: 'Total',data: this.yAxis}]};mychart.setOption(option);}}
</script><style>
</style>

三:服务端给客户端推送消息

springboot中使用@Autowired注入WebSocketServer

@Autowired
private WebSocketServer webSocketServer;

需要发消息时

 webSocketServer.sendInfo(JSONObject.toJSONString(chartValue));

四:注意

在发送信息的时候,建议转成JSON格式

客户端接收的时候要转换一下

根据个人习惯,echarts根据数据更新自动刷新,我喜欢这样写,图表不更新的时候可以尝试一下

获取到服务器的数据之后

在检查中会有json异常错误,不影响

这样写websocket是在该页面实例化一个websocket,每次刷新页面或者重新进入该页面都会新建一个websocket实例,在真实业务中很少会这样处理。所以就需要将websocket定义为全局实例,跟随vue实例的创建而创建,销毁而销毁。

需要vue使用全局websocket的朋友,可以移步 Vue-全局websockethttps://blog.csdn.net/qq_63312957/article/details/125482244?spm=1001.2014.3001.5502。

如果你恰好需要读到这篇文章,希望对你有帮助。如有写的不对或不够好的地方,欢迎指正。

WebSocket 消息推送相关推荐

  1. java socket 推送机制_Java中websocket消息推送的实现代码

    一.服务层 package com.demo.websocket; import java.io.IOException; import java.util.Iterator; import java ...

  2. node.js Websocket消息推送---GoEasy

    Goeasy, 它是一款第三方推送服务平台,使用它的API可以轻松搞定实时推送!个人感觉goeasy推送更稳定,推送速度快,代码简单易懂上手快 浏览器兼容性:GoEasy推送支持websocket 和 ...

  3. SpringBoot2.x 整合websocket 消息推送,单独发送信息,群发信息

    根据公司需求在SpringBoot项目中集成站内信,于是,我做了一个SpringBoot2.x 整合websocket 消息推送,给指定用户发送信息和群发信息即点点对方式和广播方式2种模式. 文章目录 ...

  4. GO实现websocket消息推送

    在慕课网学习了GO实现websocket消息推送,这边记录一下 依赖包: go get github.com/gorilla/websocket 然后是一个connection包 package im ...

  5. Java版WebSocket消息推送系统搭建

    Java版WebSocket消息推送系统搭建 最近在做消息推送,网上查了一些资料,开始想的是用MQ来做,后面发现用WebSocket来做的话感觉应该要简单点,话不多说,准备撸代码. 后端核心代码 /* ...

  6. WebSocket消息推送和聊天功能实现

    WebSocket消息推送 SpringBoot集成WebSocket实现消息推送和聊天Demo gradle引入依赖 测试用的Controller 两个测试页面 WebSocket的Endpoint ...

  7. java/web/springboot项目使用WebSocket消息推送

    java/web/springboot项目使用WebSocket消息推送 最近项目中,有消息推送的广播和在线咨询的功能,以前也没搞过啊,有些小伙伴估计也是,那肯定要赶紧学习起来啊~ 不说废话,今天就告 ...

  8. EasyGBS国标平台新增WebSocket消息推送,可快速定位视频播放故障

    WebSocket是建立在TCP之上的一种双向通信协议,它能实现浏览器与服务器全双工通信,在性能上具有较强的优势.尤其是在海量并发及客户端与服务器交互负载流量大的情况下,WebSocket可以极大节省 ...

  9. 微信小程序使用swoole实现websocket消息推送

    swoole我个人建议在linux环境下操作,毕竟在windows下有那么一点点麻烦.首先linux安装php和swoole环境(有手就行,建议百度). 因为我们的业务是实现消息推送,也就是在完成特定 ...

  10. 千万级WebSocket消息推送服务技术分析

    拉模式和推模式区别 拉模式(定时轮询访问接口获取数据) 数据更新频率低,则大多数的数据请求时无效的 在线用户数量多,则服务端的查询负载很高 定时轮询拉取,无法满足时效性要求 推模式(向客户端进行数据的 ...

最新文章

  1. SAP_SD常用增强
  2. 连接到多台mysql_Oracle通过dblink连接到多台MySQL
  3. 【移动开发】安卓Lab2(01)
  4. git 拉代码_一篇文章理清Git
  5. 3 当某个应用的CPU使用达到100%,该怎么办?
  6. select 和epoll模型区别
  7. 401 Palindrome
  8. matlab两张图片合成一张_11. 图像合成与图像融合
  9. Codeforces D - High Load
  10. WCF 第五章 导出并发布元数据(服务行为)
  11. 术语html的含义是,术语html指的是什么
  12. 诺基亚9.3再曝光:后置1亿像素圆形五摄 价格或超6000元
  13. linux编程排序,Linux下简单的c编程——选择法排序
  14. 【android studio】解决android studio drawable新建项目时只有一个drawable目录的问题
  15. HDU 2895 贪心 还是 大水题
  16. 【转载】深入浅出VA函数
  17. 神经网络matlab仿真,MATLAB神经网络仿真与应用_IT教程网
  18. Java判断合数或素数
  19. 传智播客黑马java 30期_黑马传智播客JavaEE57期 2019最新基础+就业+在职加薪_汇总...
  20. 移动招聘笔试计算机类,安徽移动计算机类笔试经验

热门文章

  1. U盘数据恢复软件推荐
  2. 服务器浏览器怎么打不开网页,电脑能上qq打不开网页怎么回事?
  3. 微信企业号开发之access_token接口调用示例(一)
  4. 虚化照片怎么弄?这几种方法很简单
  5. 保研计算机三级,保研干货 | 这些证书手中有,凡尔赛路任你走
  6. mysql同时满足升序和降序_mysql升序和降序语句
  7. android手机如何截屏快捷键,手机截屏怎么弄,手把手教你手机截图方法
  8. win8计算机无法安装打印机驱动程序,Win8电脑打印机驱动安装失败怎么办
  9. 【经典详解】<T> T 和 T的用法和区别,public <T> List<T> f(T a){}的详解
  10. 笔记本电脑连接无线局域网怎么设置?