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

所属分类: 软件编程 / java 阅读数: 39
收藏 0 赞 0 分享

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服务端逻辑,推送消息至服务端,然后由服务端监听,并更新数据

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

SpringBoot中使用Ehcache的详细教程

EhCache 是一个纯 Java 的进程内缓存框架,具有快速、精干等特点,是 Hibernate 中默认的 CacheProvider。这篇文章主要介绍了SpringBoot中使用Ehcache的相关知识,需要的朋友可以参考下
收藏 0 赞 0 分享

在idea 中添加和删除模块Module操作

这篇文章主要介绍了在idea 中添加和删除模块Module操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

java spring整合junit操作(有详细的分析过程)

这篇文章主要介绍了java spring整合junit操作(有详细的分析过程),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

详解JAVA 弱引用

这篇文章主要介绍了 JAVA 弱引用的相关资料,帮助大家更好的理解和学习java引用对象,感兴趣的朋友可以了解下
收藏 0 赞 0 分享

深入了解JAVA 虚引用

这篇文章主要介绍了JAVA 虚引用的相关资料,帮助大家更好的理解和学习JAVA,感兴趣的朋友可以了解下
收藏 0 赞 0 分享

详解JAVA 强引用

这篇文章主要介绍了JAVA 强引用的相关资料,帮助大家更好的理解和学习,感兴趣的朋友可以了解下
收藏 0 赞 0 分享

java中的按位与(&)用法说明

这篇文章主要介绍了java中的按位与(&)用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

深入了解JAVA 软引用

这篇文章主要介绍了JAVA 软引用的相关资料,帮助大家更好的理解和学习,感兴趣的朋友可以了解下
收藏 0 赞 0 分享

利用MyBatis实现条件查询的方法汇总

这篇文章主要给大家介绍了关于利用MyBatis实现条件查询的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者使用MyBatis具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
收藏 0 赞 0 分享

Intellij IDEA 与maven 版本不符 Unable to import maven project See logs for details: No implementation for org.apache.maven.model.path.PathTranslator was bound

这篇文章主要介绍了Intellij IDEA 与maven 版本不符 Unable to import maven project See logs for details: No implementation for org.apache.maven.model.path.Pa
收藏 0 赞 0 分享
查看更多