Vue + SpringBoot实现WebSocket通信

Vue + SpringBoot实现WebSocket通信

原文地址

服务端

  1. 在SpringBoot项目中添加ServerEndpointExporterBean的方法
@Bean
public ServerEndpointExporter exporter(){
    return new ServerEndpointExporter();
}
  1. 创建WebSocket客户端管理类:
    WebSocketComponent.java
package cn.coralcloud.blog.web.component;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author geff
 * @name WebSocketComponent
 * @description
 * @date 2019-12-18 14:22
 */
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketComponent {
    /**
     * 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;
    /**
     * concurrent包的线程安全Set,用来存放每个客户端对应的CumWebSocket对象。
     */
    private static CopyOnWriteArraySet<WebSocketComponent> webSocketSet = new CopyOnWriteArraySet<>();
    /**
     * 与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 连接建立成功调用的方法
     *
     * @param session session
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        //加入set中
        webSocketSet.add(this);
        //添加在线人数
        addOnlineCount();
        System.out.println("新连接接入。当前在线人数为:" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //从set中删除
        webSocketSet.remove(this);
        //在线数减1
        subOnlineCount();
        System.out.println("有连接关闭。当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用
     *
     * @param message message
     * @param session session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("客户端发送的消息:" + message);
        sendAll(JSON.toJSONString(messageDTO), session.getId());
    }

    /**
     * 群发
     *
     * @param message message
     */
    private static void sendAll(String message, String sessionId) {
        webSocketSet.forEach(item -> {
            if(!item.session.getId().equals(sessionId)){
                //群发
                try {
                    item.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 发生错误时调用
     *
     * @param session session
     * @param error error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("----websocket-------有异常啦");
        error.printStackTrace();
    }

    /**
     * 减少在线人数
     */
    private void subOnlineCount() {
        WebSocketComponent.onlineCount--;
    }

    /**
     * 添加在线人数
     */
    private void addOnlineCount() {
        WebSocketComponent.onlineCount++;
    }

    /**
     * 当前在线人数
     *
     * @return int
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    /**
     * 发送信息
     *
     * @param message message
     * throws IOException
     */
    public void sendMessage(String message) throws IOException {
        //获取session远程基本连接发送文本消息
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        WebSocketComponent that = (WebSocketComponent) o;
        return Objects.equals(session, that.session);
    }

    @Override
    public int hashCode() {
        return Objects.hash(session);
    }
}

@ServerEndpoint 注解标识当前WebSocket服务端endpoint地址, 本文实际前端访问的ws地址为: ws://localhost:8080/websocket
至此, 服务端工作完成。

页面VUE端

<template>
  <el-card v-loading="loading" element-loading-spinner="el-icon-loading" :body-style="{padding: '5px',backgroundColor: '#eee'}" class="socket-box" shadow="hover">
    <div class="socket-box__content" :style="{height: (boxHeight - 125) + 'px'}" id="socket-content">
      <div v-if="hasMore" @click="loadMore" class="load-more">
        <span>加载更多</span>
      </div>
      <div v-else style="width: 100%;text-align: center;font-size: 12px">没有更多了</div>
      <div class="item" v-for="m in messages" :class="checkMe(m) ? 'sender' : ''">
        <div class="slide">
          <div class="avatar" :style="{background: m.background}">{{m.name.substring(0, 1)}}</div>
          <div class="meta">
            <div class="name">{{m.name}}</div>
            <div class="date">{{m.createTime|datetime}}</div>
          </div>
        </div>
        <p>{{m.content}}</p>
      </div>
    </div>
    <div class="socket-box__footer">
      <el-form @submit.native.prevent>
        <el-form-item>
          <el-input type="textarea" resize="none" :rows="3" :disabled="!connect"
                    :placeholder="connect ? '输入内容...' : '当前连接断开, 请刷新重试! '" :clearable="true" v-model="message"
                    @keydown.native.enter="submitMsgForm"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="sendMsg(message)" :disabled="!connect" style="width: 100%" type="primary" size="small">发送 (Enter)</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
    import {GET} from "@/api";

    export default {
      name: "Chatroom",
      data(){

        return {
          messages: [],
          message: '',
          // boxHeight: document.documentElement.clientHeight - 85,
          hasMore: true,
          pager: {pageNo: 1, pageSize: 10, total: 0},
          loading: false,
          connect: false
        }
      },
      props: {
        boxHeight: {
          type: Number,
          required: true
        }
      },
      methods: {

        submitMsgForm(event){
          if(event.shiftKey){
            return;
          }
          event.preventDefault();
          this.sendMsg(this.message)
        },
        checkMe(message){
          let user = localStorage.getItem("socketUser");
          if(user){
            user = JSON.parse(user);
            return user.uid === message.uid
          } else {
            return false;
          }
        },
        initWebSocket: function () {
          this.websock = new WebSocket(`ws://localhost:8080/websocket`);
          this.websock.onopen = this.websocketonopen;
          this.websock.onerror = this.websocketonerror;
          this.websock.onmessage = this.websocketonmessage;
          this.websock.onclose = this.websocketclose;
          const that = this;
          that.loading = true;
          GET({
            url: '/api/personal/web/message/socketData?pageNo=1',
            callback: res => {
              if(res.code === 200){
                that.messages = res.data.messages;
                that.hasMore = res.data.messages.length === that.pager.pageSize;
                that.$nextTick(function () {
                  document.getElementById("socket-content").scroll({
                    top: document.getElementById("socket-content").scrollHeight,
                    left: 0,
                    behavior: 'smooth'
                  })
                })
              }
              that.loading=false
            }
          })
        },
        sendMsg(data){
          if(/^\s*$/.test(data)){
            this.message = '';
            return;
          }
          // 发送时传入JSON(UID, 昵称, 内容)
          const local = localStorage.getItem("socketUser");
          if(local){
            const l = JSON.parse(local);
            this.send(l, data)
          } else {
            // 弹框
            this.$prompt('首次发表, 请输入昵称', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
            }).then(({ value }) => {
              // 随机生成UID
              const uid = this.randomVideoUuid(32, 16);
              const form = {
                uid: uid,
                name: value,
                background: `rgb(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})`
              };
              localStorage.setItem("socketUser", JSON.stringify(form));
              this.send(form, data)
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '取消输入'
              });
            });
          }
        },
        send(obj, data){
          obj.content = data;
          obj.createTime = new Date().getTime();
          this.websock.send(JSON.stringify(obj));
          this.message = '';
          this.messages.push(obj);
          this.$nextTick(function () {
            document.getElementById("socket-content").scroll({
              top: document.getElementById("socket-content").scrollHeight,
              left: 0,
              behavior: 'smooth'
            })
          })
        },
        loadMore(){
          this.loading = true;
          const that = this;
          if(this.hasMore){
            this.pager.pageNo += 1;
            GET({
              url: '/api/personal/web/message/socketData?pageNo=' + this.pager.pageNo,
              callback: res => {
                if(res.code === 200){
                  that.messages = [...res.data.messages, ...that.messages];
                  that.hasMore = res.data.messages.length >= that.pager.pageSize;
                }
                that.loading = false;
              }
            })
          }
        },
        websocketonopen: function (e) {
          console.log("WebSocket连接成功", e);
          this.connect = true;
        },
        websocketonerror: function (e) {
          console.log("WebSocket连接发生错误");
          this.connect = false;
        },
        websocketonmessage: function (e) {
          const da = JSON.parse(e.data);
          this.messages.push(da);
          this.$nextTick(function () {
            document.getElementById("socket-content").scroll({
              top: document.getElementById("socket-content").scrollHeight,
              left: 0,
              behavior: 'smooth'
            })
          })
        },
        websocketclose: function (e) {
          console.log("connection closed (" + e.code + ")");
        },
        randomVideoUuid(len, radix) {
          let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
          let uuid = [];
          radix = radix || chars.length;
          if (len) {
            for (let i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
          } else {
            let r;
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';
            for (let i = 0; i < 36; i++) {
              if (!uuid[i]) {
                r = 0 | Math.random()*16;
                uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r];
              }
            }
          }
          return uuid.join('');
        },
      },
      mounted() {
        this.initWebSocket();
      }
    }
</script>

本段代码为简单的Vue实现的网页聊天室代码, 其中@/api为自己简单封装的JS函数, 用户初次进入页面时会生成一个随机UID保存到localStorage中,在mounted周期中初始化websocket连接。本聊天室最终效果地址: https://web.coralcloud.cn/blog/message

你可能感兴趣的:(Vue + SpringBoot实现WebSocket通信)