前言
公司项目需要用到消息提示,那么WebSocket它来了经过我面向百度的学习,废话不多说直接开干.
后端搭建
一、依赖导入
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>二、搭建websocket服务
1.WebSocketConfig配置文件
/*==============================================================================
 = - Yang Buyi  Copyright (c) 2021 https://yangbuyi.top.
 =============================================================================*/
package top.yangbuyi.service_websocket.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
 * 配置文件
 *
 * @author Yang Buyi
 * @date 2021/10/25
 */
public class WebSocketConfig {
  /**
   * 给Spring容器注入 ServerEndpointExporter 对象
   *
   * @return {@link ServerEndpointExporter}
   */
  
  public ServerEndpointExporter serverEndpointExporter() {
    return new ServerEndpointExporter();
  }
}2.WebSocketServer服务
/*==============================================================================
 = - Yang Buyi  Copyright (c) 2021 https://yangbuyi.top.
 =============================================================================*/
package top.yangbuyi.service_websocket.server;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArraySet;
/**
 * websocket前端请求服务地址
 *
 * /service_websocket/wspoint/yangbuyi
 *
 * @author Yang Buyi
 * @date 2021/10/25
 */
("/service_websocket/wspoint/{loginName}")
public class WebSocketServer {
    /**
     * 存储每一个连接
     */
    private static final CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
    /**
     * 会话
     */
    private Session session;
    /**
     * 登录名
     */
    private String loginName = "";
    /**
     * 在开放
     *
     * @param session   会话
     * @param loginName 登录名
     */
    
    public void onOpen(Session session, ("loginName") String loginName) {
        // 前端连接得到登陆名称
        this.loginName = loginName;
        // 当前websokcet生成的会话
        this.session = session;
        webSocketSet.add(this);
        try {
            sendMessage("success");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    /**
     * 在关闭
     */
    
    public void onClose() {
        webSocketSet.remove(this);
    }
    /**
     * 在消息
     *
     * @param message 消息
     * @param session 会话
     */
    
    public void onMessage(String message, Session session) {
        System.out.println("接收到来自[" + message + "]发送的消息" + session);
        // 发送消息
//        for (WebSocketServer item : webSocketSet) {
//            try {
//                item.sendMessage(message + ",时间:" + new Date() + session);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
    }
    /**
     * 在错误
     *
     * @param session 会话
     * @param error   错误
     */
    
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }
    /**
     * 发送消息
     *
     * @param message 消息
     */
    public void sendMessage(String message) {
        try {
             // 建议加个同步锁 
            if (this.session != null) {
                this.session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 发送信息
     * 发送指定消息给某个用户
     *
     * @param userName 用户名
     * @param msgStr   消息信息
     */
    public static void sendInfo(String userName, String msgStr) {
        for (WebSocketServer item : webSocketSet) {
            if (item.loginName.equals(userName)) {
                item.sendMessage(msgStr);
            }
        }
    }
}前端搭建
一、index.vue
<!--============================================================================
  = - Yang Buyi  Copyright (c) 2021 https://yangbuyi.top.
  ===========================================================================-->
<template>
  <div class="webSocket">
    <button id="send" class="btn btn-default" ="sendMsg('发送杨不易https://yangbuyi.top')">Send</button>
    <div v-for="item in msgData" :key="item">
      {{ item }}
    </div>
  </div>
</template>
<script>
export default {
  name: 'WebSocket',
  data() {
    return {
      // 消息
      msgData: [],
      websocket: null
    }
  },
  mounted() {
    this.connection()
    // this.initWebSocket()
  },
  destroyed() {
    if (this.websocket != null) this.websocket.close() // 离开路由之后断开websocket连接
  },
  methods: {
    initWebSocket() {
      this.connection()
      // const that = this
      // // 断开重连机制,尝试发送消息,捕获异常发生时重连
      // this.timer = setInterval(() => {
      //   try {
      //     that.websocket.send('hello')
      //   } catch (err) {
      //     console.log('断线了: ' + err)
      //     that.connection()
      //   }
      // }, 5000)
    },
    /**
     * 连接后台ws
     */
    connection() {
      const socketUrl = 'ws://localhost:你服务的端口/service_websocket/wspoint/' + '唯一名称'
      if (typeof (WebSocket) === 'undefined') {
        console.log('您的浏览器不支持WebSocket')
        this.$message.error('您的浏览器不支持WebSocket,无法使用推送功能!')
      } else {
        this.websocket = new WebSocket(socketUrl)
        console.log(this.websocket)
        this.websocket.onopen = this.websocketOnopen // 连接成功
        this.websocket.onmessage = this.websocketOnmessage // 广播成功
        this.websocket.onerror = this.websocketOnerror // 连接断开,失败
        this.websocket.onclose = this.websocketClose // 连接关闭
      }
    },
    websocketOnopen() {
      this.sendMsg('连接成功第一次https://yangbuyi.top')
      console.log('连接成功')
    },
    websocketOnerror() {
      console.log('连接失败')
    },
    websocketClose() {
      console.log('断开连接')
    },
    websocketOnmessage(data) {
      this.msgData.push(data)
    },
    sendMsg(val) {
      this.websocket.send(val)
    }
  }
}
</script>你的压力来源于无法自律,只是假装努力,现状跟不上内心欲望,所以你焦虑又恐慌。——杨不易










