分享

spring-boot(九)websocket配置

 关平藏书 2018-01-12

从servlet3.0开始就已经支持websocket了,现在已经在很多场景广泛的使用.
下面介绍下spring-boot如何配置websocket支持

先看下官网给出的指导意见
QQ截图20161230141746.png

其实官方给的这个文档很简单,关于spring对websocket所做的支持在boot中未作详细说明,但是这并不影响我们来学习.在spring-framework框架中有非常详细的使用说明.想非常透彻的了解spring-websocket请自行学习.

这里仅对整合做出演示. 案例代码在 spring-boot(八)和spring-session集成 集成上进行改造

项目结构图

QQ截图20161230142457.png

在pom中加入依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-websocket</artifactId>
  4. </dependency>

在文件夹 hello/websocket 下建立 MyHandler.javaWebSocketConfig.java

  • MyHandler.java
  1. package hello.websocket;
  2. import org.springframework.web.socket.TextMessage;
  3. import org.springframework.web.socket.WebSocketSession;
  4. import org.springframework.web.socket.handler.TextWebSocketHandler;
  5. /**
  6. * @author majinding888@foxmail.com
  7. * @date 2016-12-30 下午1:35:45
  8. */
  9. public class MyHandler extends TextWebSocketHandler {
  10. @Override
  11. protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
  12. session.sendMessage(new TextMessage("服务器的时间: " + System.currentTimeMillis()));
  13. }
  14. }
  • WebSocketConfig.java
  1. package hello.websocket;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.socket.WebSocketHandler;
  5. import org.springframework.web.socket.config.annotation.EnableWebSocket;
  6. import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
  7. import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
  8. /**
  9. * @author majinding888@foxmail.com
  10. * @date 2016-12-30 下午1:38:37
  11. */
  12. @Configuration
  13. @EnableWebSocket
  14. public class WebSocketConfig implements WebSocketConfigurer {
  15. @Override
  16. public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
  17. registry.addHandler(myHandler(), "/myHandler").withSockJS();
  18. }
  19. @Bean
  20. public WebSocketHandler myHandler() {
  21. return new MyHandler();
  22. }
  23. }

注意此处的注解 @Configuration , @EnableWebSocket


其实环境搭建到此已经结束了,为了测试我们还需要页面来发送消息. 页面部分的代码就不做过多结束了,在tomcat7及以上版本都有examples文件夹,里面有websocket的测试页面,直接将echo.html页面复制到目录 /static 下.
启动主启动类,打开浏览器访问 http://localhost:666/echo.html
QQ截图20161230143920.png

源代码附件地址: my-springboot-9.zip

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多