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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Vue(前端框架)和Spring Boot后端框架)结合起来实现websocket双工通信的步骤如下: 1. 首先,在Vue项目中安装`vue-native-websocket`插件。这个插件能够帮助我们在Vue中使用websocket。 2. 在Vue项目的根目录下创建一个文件,例如`webSocket.js`,在这个文件中,引入`vue-native-websocket`插件,并配置websocket服务的地址和端口号。 3. 在Vue项目的入口文件(例如`main.js`)中,引入`webSocket.js`文件,并将websocket插件注册到Vue实例中。 4. 在Vue组件中,使用`this.$socket`来访问websocket对象。可以使用`this.$socket.send()`方法发送消息给后端。 5. 在Spring Boot项目中,添加`spring-boot-starter-websocket`的依赖。 6. 创建一个继承自`WebSocketConfigurer`接口的类,并实现其中的`registerWebSocketHandlers`方法。在该方法中,注册一个`WebSocketHandler`来处理前端与后端之间的websocket连接和消息传递逻辑。 7. 在`WebSocketHandler`中,重写`handleTextMessage`方法来处理接收到的文本消息。可以在这个方法中进行消息的处理逻辑,例如广播消息给所有连接的客户端。 8. 在Spring Boot的配置类(例如`Application.java`)中,添加`@EnableWebSocket`来启用websocket支持。 9. 启动Spring Boot项目,并运行Vue项目。此时,前端可以使用websocket连接后端,并进行双工通信。前端可以通过`this.$socket.send()`方法发送消息给后端后端可以通过`WebSocketHandler`接收处理并响应消息给前端。 以上就是使用VueSpring Boot实现websocket双工通信的基本步骤。通过这种方式,前端和后端可以实时地进行双向通信,方便实现一些实时推送、聊天室等功能。 ### 回答2: VueSpring Boot结合实现WebSocket双工通信的步骤如下: 1. 在Vue项目中安装Vue-socket.io插件,可以在Vue项目的根目录下运行以下命令进行安装: ``` npm install --save vue-socket.io ``` 2. 在Vue项目的main.js文件中引入Vue-socket.io插件,并配置socket连接: ```javascript import VueSocketIO from 'vue-socket.io' import SocketIO from 'socket.io-client' Vue.use(new VueSocketIO({ debug: true, connection: SocketIO('http://localhost:8080'), // 这里的地址需要修改为后端的IP地址和端口号 })) ``` 3. 在Vue组件中使用WebSocket进行通信,例如,在Vue组件的created钩子中: ```javascript created() { this.$socket.emit('register', { userId: 123 }) // 发送注册消息给后端 this.$socket.on('message', (data) => { // 监听后端发送的消息 console.log('收到消息:', data) }) } ``` 4. 在Spring Boot中编写WebSocket后端控制器,处理前端发送的消息,并实现双工通信,例如: ```java @Controller public class WebSocketController { @Autowired private SimpMessagingTemplate messagingTemplate; @MessageMapping("/register") public void registerUser(@Payload Map<String, Long> payload) { // 处理注册逻辑,例如保存用户ID等 Long userId = payload.get("userId"); // 广播消息给所有连接的用户 messagingTemplate.convertAndSend("/topic/message", "用户 " + userId + " 加入了聊天室"); } // 其他接口处理逻辑... } ``` 5. 在Spring Boot中配置WebSocket相关的bean,例如,在配置类中添加以下配置: ```java @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableSimpleBroker("/topic"); // 消息代理前缀 registry.setApplicationDestinationPrefixes("/app"); // 应用消息前缀 } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS(); } } ``` 以上是VueSpring Boot实现WebSocket双工通信的基本步骤,当前端发送消息到后端时,后端可以处理并向所有连接的客户端发送广播消息,实现实时的双工通信。 ### 回答3: VueSpring Boot均提供了支持WebSocket的功能,通过结合VueSpring Boot,我们可以实现WebSocket双工通信。 首先,在Vue项目中使用Vue提供的WebSocket API建立与后端WebSocket连接,可以使用Vue的mounted生命周期钩子函数来实现这一步骤。通过WebSocket连接后,我们可以使用VueWebSocket对象来发送数据给后端,同时监听后端的数据。 在后端,我们使用Spring Boot提供的WebSocket支持来处理前端的请求。首先,在Spring Boot的配置文件中,我们需要开启WebSocket功能。然后,我们可以通过创建一个WebSocketHandler类来处理前端的请求和发送消息给前端。在WebSocketHandler中,我们可以实现OnOpen、OnMessage、OnClose等方法来处理前端的连接、接收消息和关闭连接。在接收到消息后,我们可以编写相应的业务逻辑,如处理前端发送的数据,然后将处理结果发送给前端。 通过上述步骤,我们实现VueSpring Boot之间的WebSocket双工通信。前端可以通过VueWebSocket对象与后端进行实时的双向通信后端可以处理前端的请求并发送相应的消息给前端。这使得实时的数据交互和通信成为可能,为应用程序添加了更多实时性和交互性。 需要注意的是,在实现WebSocket通信时,我们需要确保VueSpring Boot的版本兼容,并且正确配置相关的依赖和配置文件。同时,我们还需要考虑到安全性和性能等方面的因素,如认证和授权、连接数限制等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值