网站建设定制开发WebSocket 消息推送

目录


一:SpringBoot网站建设定制开发后端建立服务器 

1.SpringBoot使用WebSocket准备

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-websocket</artifactId>
  4. </dependency>

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

  1. @Configuration
  2. public class WebSocketConfig {
  3. @Bean
  4. public ServerEndpointExporter serverEndpointExporter() {
  5. return new ServerEndpointExporter();
  6. }
  7. }

3.创建WebSocketServer实体类 添加 @ServerEndpoint注解 value 网站建设定制开发即是前端访问的接口

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

我的代码如下

  1. @Slf4j
  2. //@ServerEndpoint("/api/websocket/{user}") 根据自己的需求选择合适的
  3. @ServerEndpoint(value = "/api/websocket")
  4. @Component
  5. public class WebSocketServer {
  6. private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
  7. // private static Map<String , Session> sessionMap = new ConcurrentHashMap<>();
  8. private Session session;
  9. // 连接建立成功调用的方法
  10. @OnOpen
  11. public void onOpen(Session session) {
  12. this.session = session;
  13. webSocketSet.add(this);
  14. addOnlineCount();
  15. try {
  16. sendMessage("连接成功");
  17. } catch (IOException e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. // 此方法是将用户与对应session绑定,用于推送消息给指定用户
  22. // @OnOpen
  23. // public void onOpen(@PathParam("user") String user, Session session) {
  24. // currentUser = user;
  25. // System.out.println("Connected ... " + session.getId());
  26. // }
  27. //连接关闭调用的方法
  28. @OnClose
  29. public void onClose() {
  30. webSocketSet.remove(this);
  31. }
  32. //接收客户端消息
  33. // @OnMessage
  34. // public void onMessage(String message, Session session) {
  35. // log.info(message);
  36. // }
  37. //
  38. @OnError
  39. public void onError(Session session, Throwable error) {
  40. log.error("发生错误");
  41. error.printStackTrace();
  42. }
  43. public void sendMessage(String message) throws IOException {
  44. this.session.getBasicRemote().sendText(message);
  45. }
  46. //将消息推送给所有客户端
  47. public void sendInfo(String message) throws IOException {
  48. log.info(message);
  49. for (WebSocketServer item : webSocketSet) {
  50. try {
  51. item.sendMessage(message);
  52. } catch (IOException e) {
  53. continue;
  54. }
  55. }
  56. }
  57. }

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

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

        npm install -websocket 引入webcoket 

        main.js中引用

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

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

  1. <template>
  2. <div>
  3. <div id="chart" style="width: 700px; height: 200px;"></div>
  4. </div>
  5. </template>
  6. <script>
  7. export default{
  8. name:"chart",
  9. data(){
  10. return{
  11. scoket:'',
  12. yAxis:[],
  13. xAxis:[],
  14. }
  15. },
  16. mounted() {
  17. this.chart();
  18. this.init();
  19. },
  20. methods:{
  21. //初始化websocket实例
  22. init: function () {
  23. if(typeof(WebSocket) === "undefined"){
  24. alert("您的浏览器不支持socket")
  25. }else{
  26. // 实例化socket
  27. this.socket = new WebSocket("ws://192.168.1.21:8082/api/websocket")
  28. // 监听socket连接
  29. this.socket.onopen = this.open
  30. // 监听socket错误信息
  31. this.socket.onerror = this.error
  32. // 监听socket消息
  33. this.socket.onmessage = this.getMessage
  34. }
  35. },
  36. open: function () {
  37. console.log("socket连接成功")
  38. },
  39. error: function () {
  40. console.log("连接错误")
  41. },
  42. //接收服务器发来的消息
  43. getMessage: function (e) {
  44. console.log(e.data);
  45. this.xAxis = JSON.parse(e.data).xAxis;
  46. this.yAxis = JSON.parse(e.data).yAxis;
  47. this.chart();
  48. },
  49. //给服务器发消息的方法
  50. send: function () {
  51. this.socket.send(this.parms);
  52. },
  53. close: function () {
  54. console.log("socket已经关闭")
  55. },
  56. chart(){
  57. //有的话就获取已有echarts实例的DOM节点。
  58. var mychart = this.$echarts.getInstanceByDom(document.getElementById('timechart'));
  59. if (mychart == null) { // 如果不存在,就进行初始化。
  60. mychart = this.$echarts.init(document.getElementById('chart'));
  61. }
  62. var option = {
  63. title: {
  64. text: '时间(ms)/阶段'
  65. },
  66. tooltip: {
  67. trigger: 'axis'
  68. },
  69. legend: {
  70. // data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
  71. },
  72. grid: {
  73. left: '3%',
  74. right: '4%',
  75. bottom: '3%',
  76. containLabel: true
  77. },
  78. toolbox: {
  79. feature: {
  80. saveAsImage: {}
  81. }
  82. },
  83. xAxis: {
  84. type: 'category',
  85. boundaryGap: false,
  86. data: this.xAxis
  87. },
  88. yAxis: {
  89. type: 'value'
  90. },
  91. series: [
  92. {
  93. type: 'line',
  94. stack: 'Total',
  95. data: this.yAxis
  96. }
  97. ]
  98. };
  99. mychart.setOption(option);
  100. }
  101. }
  102. </script>
  103. <style>
  104. </style>

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

springboot中使用@Autowired注入WebSocketServer

  1. @Autowired
  2. private WebSocketServer webSocketServer;

需要发消息时  

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

四:注意

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

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

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

获取到服务器的数据之后

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

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

需要vue使用全局websocket的朋友,可以移步 。

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

网站建设定制开发 软件系统开发定制 定制软件开发 软件开发定制 定制app开发 app开发定制 app开发定制公司 电商商城定制开发 定制小程序开发 定制开发小程序 客户管理系统开发定制 定制网站 定制开发 crm开发定制 开发公司 小程序开发定制 定制软件 收款定制开发 企业网站定制开发 定制化开发 android系统定制开发 定制小程序开发费用 定制设计 专注app软件定制开发 软件开发定制定制 知名网站建设定制 软件定制开发供应商 应用系统定制开发 软件系统定制开发 企业管理系统定制开发 系统定制开发