springboot vue websocket springboot+vue实现websocket配置过程解析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

springboot vue websocket springboot+vue实现websocket配置过程解析

Nutri-Express   2021-04-21 我要评论

1.引入依赖

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

2.配置ServerEndpointExporter

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

}

这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。

3.创建websocket的ServerEndpoint端点

@Component
@ServerEndpoint("/socket")
public class WebSocketServer {
  /**
   * 全部在线会话 
   */
  private static Map<String, Session> onlineSessions = new ConcurrentHashMap<>();


  /**
   * 当客户端打开连接:1.添加会话对象 2.更新在线人数
   */
  @OnOpen
  public void onOpen(Session session) {
    onlineSessions.put(session.getId(), session);
    
  }

  /**
   * 当客户端发送消息:1.获取它的用户名和消息 2.发送消息给所有人
   * <p>
   * PS: 这里约定传递的消息为JSON字符串 方便传递更多参数!
   */
  @OnMessage
  public void onMessage(Session session, String jsonStr) {
    
  }

  /**
   * 当关闭连接:1.移除会话对象 2.更新在线人数
   */
  @OnClose
  public void onClose(Session session) {
    onlineSessions.remove(session.getId());
    
  }

  /**
   * 当通信发生异常:打印错误日志
   */
  @OnError
  public void onError(Session session, Throwable error) {
    error.printStackTrace();
  }

  /**
   * 公共方法:发送信息给所有人
   */
  public void sendMessageToAll(String jsonMsg) {
    onlineSessions.forEach((id, session) -> {
      try {
        session.getBasicRemote().sendText(jsonMsg);
      } catch (IOException e) {
        e.printStackTrace();
      }
    });
  }

}

4.前端配置连接与接收消息

<script>
import Vue from 'vue'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css'; // 默认主题

Vue.use(ElementUI, {size: 'small'});

import '@/directives/directives.js'
import Locale from '@/mixins/locale';
import { t } from '@/locale';


  /**
   * WebSocket客户端
   *
   * 使用说明:
   * 1、WebSocket客户端通过回调函数来接收服务端消息。例如:webSocket.onmessage
   * 2、WebSocket客户端通过send方法来发送消息给服务端。例如:webSocket.send();
   */
  function getWebSocket() {
    /**
     * WebSocket客户端 PS:URL开头表示WebSocket协议 中间是域名端口 结尾是服务端映射地址
     */
    var webSocket = new WebSocket('ws://10.10.10.3:9117/socket');//建立与服务端的连接
    /**
     * 当服务端打开连接
     */
    webSocket.onopen = function (event) {
      console.log('WebSocket打开连接');
    };

    /**
     * 当服务端发来消息:1.广播消息 2.更新在线人数
     */
    webSocket.onmessage = function (event) {
      console.log(event)
      console.log('WebSocket收到消息:%c' + event.data, 'color:green');
      //获取服务端消息
      var message = JSON.parse(event.data) || {};
      console.log(message)//
    };

    /**
     * 关闭连接
     */
    webSocket.onclose = function (event) {
      console.log('WebSocket关闭连接');
    };

    /**
     * 通信失败
     */
    webSocket.onerror = function (event) {
      console.log('WebSocket发生异常');

    };
    return webSocket;
  }

  var webSocket = getWebSocket();


  /**
   * 通过WebSocket对象发送消息给服务端
   * 此处没有主动发消息给服务端,如果调用此方法,则会发送消息至socket服务端onMessage()方法上
   */
  function sendMsgToServer() {
    var $message = $('#msg');
    if ($message.val()) {
      webSocket.send(JSON.stringify({username: $('#username').text(), msg: $message.val()}));
      $message.val(null);
    }

  }
export default {
 
}

5.实现后端推送消息至浏览器端

  @Autowired
  private WebSocketServer webSocketServer;//注入socket服务
  
  @Override
  public PuStatesResult queryPuStateUseInfo(QueryCondition condition) {
    String sql = condition.generatorSql();
    if(sql == null){
      return null;
    }
    List<PuState> puStateList = null;
    puStateList = puStateMapper.getPusBySql(sql);
    if(puStateList == null || puStateList.size() == 0){
      return null;
    }
    PuStatesResult result = new PuStatesResult();
    result.setPuStateList(puStateList);
    result.computePuStates();
    if(false == condition.isWithDetail()){
      result.setPuStateList(null);
    }
    //todo
    Gson gson = new Gson();
    String json = gson.toJson(result);
    webSocketServer.sendMessageToAll(json);//调用第3节中的方法
    return result;
  }

此处是前端查询时,服务器将一些数据发送至前端,假如我们在实现有些前端数据显示的时候,当查询一次后,如果没有断开连接,希望后端数据更新后,前端能接收最近数据。那么可以在数据更新接口中,调用自己实现的socket服务端逻辑,推送消息至服务端,然后由服务端监听,并更新数据

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们