1、新建maven工程

工程结构如下:

完整的pom.xml如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6.  
  7. <groupId>com.websocket.demo</groupId>
  8. <artifactId>websocket-demo</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <parent>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-parent</artifactId>
  13. <version>1.4.1.RELEASE</version>
  14. </parent>
  15. <dependencies>
  16. <!-- thymeleaf 模板的配置 -->
  17. <dependency>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-web</artifactId>
  24. </dependency>
  25. <!-- spring websocket的配置 -->
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-websocket</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-devtools</artifactId>
  33. <scope>runtime</scope>
  34. </dependency>
  35. <dependency>
  36. <groupId>org.springframework.boot</groupId>
  37. <artifactId>spring-boot-autoconfigure</artifactId>
  38. <version>1.4.5.RELEASE</version>
  39. </dependency>
  40. </dependencies>
  41. <build>
  42. <plugins>
  43. <plugin>
  44. <groupId>org.springframework.boot</groupId>
  45. <artifactId>spring-boot-maven-plugin</artifactId>
  46. </plugin>
  47. </plugins>
  48. </build>
  49. </project>

2、application.properties 的配置如下

  1. #thymeleaf start
  2. #spring.thymeleaf.mode=HTML5
  3. spring.thymeleaf.encoding=UTF-8
  4. spring.thymeleaf.content-type=text/html
  5. #开发时关闭缓存,不然没法看到实时页面
  6. spring.thymeleaf.cache=false
  7. spring.thymeleaf.prefix=classpath:/templates/
  8. #thymeleaf end
  9.  
  10. server.port=8082

3、启动类

  1. package com.websocket;
  2.  
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5.  
  6. /**
  7. * @author Administrator
  8. * @date 2018/08/18
  9. */
  10. @SpringBootApplication
  11. public class Application {
  12. public static void main(String[] args) throws Exception {
  13. SpringApplication.run(Application.class, args);
  14. }
  15. }

4、WebsocketConfig 类进行了websocket的配置

  1. package com.websocket.config;
  2.  
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.messaging.simp.config.MessageBrokerRegistry;
  5. import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
  6. import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
  7. import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
  8.  
  9. /**
  10. * @author hzb
  11. * @date 2018/09/30
  12. */
  13. @Configuration
  14. @EnableWebSocketMessageBroker
  15. public class WebsocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
  16.  
  17. @Override
  18. public void configureMessageBroker(MessageBrokerRegistry config) {
  19. //启用/userTest,/topicTest,两个消息前缀
  20. config.enableSimpleBroker("/userTest","/topicTest");
  21. //如果不设置下面这一句,用convertAndSendToUser来发送消息,前端订阅只能用/user开头。
  22. config.setUserDestinationPrefix("/userTest");
  23. //客户端(html等)向服务端发送消息的前缀
  24. config.setApplicationDestinationPrefixes("/app");
  25. }
  26. @Override
  27. public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
  28. //客户端和服务端进行连接的endpoint
  29. stompEndpointRegistry.addEndpoint("/websocket-endpoint").setAllowedOrigins("*").withSockJS();
  30. }
  31. }

5、消息管理实现类

  1. package com.websocket.controller;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.messaging.handler.annotation.MessageMapping;
  5. import org.springframework.messaging.handler.annotation.SendTo;
  6. import org.springframework.messaging.simp.SimpMessagingTemplate;
  7. import org.springframework.scheduling.annotation.EnableScheduling;
  8. import org.springframework.scheduling.annotation.Scheduled;
  9. import org.springframework.stereotype.Controller;
  10. import org.springframework.web.bind.annotation.GetMapping;
  11.  
  12. import java.text.DateFormat;
  13. import java.text.SimpleDateFormat;
  14. import java.util.Date;
  15.  
  16. /**
  17. * @author hzb
  18. * @date 2018/09/30
  19. */
  20. @Controller
  21. @EnableScheduling
  22. public class WebsocketMsgController {
  23.  
  24. @Autowired
  25. private SimpMessagingTemplate messagingTemplate;
  26.  
  27. @GetMapping("/")
  28. public String index() {
  29. return "index";
  30. }
  31.  
  32. /**
  33. * index.html将message发送给后端,后端再将消息重组后发送到/topicTest/web-to-server-to-web
  34. * @param message
  35. * @return
  36. * @throws Exception
  37. */
  38. @MessageMapping("/send")
  39. @SendTo("/topicTest/web-to-server-to-web")
  40. public String send(String message) throws Exception {
  41. DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  42. return "服务器将原消息返回: "+df.format(new Date())+" :" + message;
  43. }
  44.  
  45. /**
  46. * 最基本的服务器端主动推送消息给前端
  47. * @return
  48. * @throws Exception
  49. */
  50. @Scheduled(fixedRate = 1000)
  51. public String serverTime() throws Exception {
  52. // 发现消息
  53. DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  54. messagingTemplate.convertAndSend("/topicTest/servertime", df.format(new Date()));
  55. return "servertime";
  56. }
  57.  
  58. /**
  59. * 以下面这种方式发送消息,前端订阅消息的方式为: stompClient.subscribe('/userTest/hzb/info'
  60. * @return
  61. * @throws Exception
  62. */
  63. @Scheduled(fixedRate = 1000)
  64. public String serverTimeToUser() throws Exception {
  65. // 发现消息
  66. DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  67. //这里虽然没有指定发送前缀为/userTest,但是在WebsocketConfig.java中设置了config.setUserDestinationPrefix("/userTest"),
  68. //否则默认为/user
  69. messagingTemplate.convertAndSendToUser("hzb","/info", df.format(new Date()));
  70. return "serverTimeToUser";
  71. }
  72. }

前端代码:index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>玩转spring boot——websocket</title>
  5. <script src="//cdn.bootcss.com/angular.js/1.5.6/angular.min.js"></script>
  6. <script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
  7. <script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
  8. <script type="text/javascript">
  9. var stompClient = null;
  10.  
  11. var app = angular.module('app', []);
  12. app.controller('MainController', function($rootScope, $scope, $http) {
  13.  
  14. $scope.data = {
  15. connected : false,
  16. sendMessage : '',
  17. receivMessages : []
  18. };
  19.  
  20. //连接
  21. $scope.connect = function() {
  22. var socket = new SockJS('/websocket-endpoint');
  23. stompClient = Stomp.over(socket);
  24. stompClient.connect({}, function(frame) {
  25. // 订阅后端主动推消息到前端的topic
  26. stompClient.subscribe('/topicTest/servertime', function(r) {
  27. $scope.data.time = '当前服务器时间:' + r.body;
  28. $scope.data.connected = true;
  29. $scope.$apply();
  30. });
  31. // 阅后端主动推消息到前端的topic,只有指定的用户(hzb)收到的的消息
  32. stompClient.subscribe('/userTest/hzb/info', function(r) {
  33. $scope.data.hzbtime = '当前服务器时间:' + r.body;
  34. $scope.data.connected = true;
  35. $scope.$apply();
  36. });
  37. // 订阅前端发到后台,后台又将消息返回前台的topic
  38. stompClient.subscribe('/topicTest/web-to-server-to-web', function(msg) {
  39. $scope.data.receivMessages.push(msg.body);
  40. $scope.data.connected = true;
  41. $scope.$apply();
  42. });
  43.  
  44. $scope.data.connected = true;
  45. $scope.$apply();
  46. });
  47. };
  48.  
  49. $scope.disconnect = function() {
  50. if (stompClient != null) {
  51. stompClient.disconnect();
  52. }
  53. $scope.data.connected = false;
  54. }
  55.  
  56. $scope.send = function() {
  57. stompClient.send("/app/send", {}, JSON.stringify({
  58. 'message' : $scope.data.sendMessage
  59. }));
  60. }
  61. });
  62. </script>
  63. </head>
  64. <body ng-app="app" ng-controller="MainController">
  65.  
  66.   <h2>websocket示例</h2> 
  67.   <label>WebSocket连接状态:</label>
  68.   <button type="button" ng-disabled="data.connected" ng-click="connect()">连接</button>
  69.   <button type="button" ng-click="disconnect()" ng-disabled="!data.connected">断开</button>
  70.   <br/>
  71.   <br/>
  72.   <div ng-show="data.connected">
  73. <h4>以下是websocket的服务端主动推送消息到页面的例子</h4>
  74.     <label>{{data.time}}</label> <br/> <br/>
  75. </div>
  76.   <div ng-show="data.connected">
  77. <h4>以下是websocket的服务端主动推送消息到页面的例子,只有hzb这个用户收到</h4>
  78.     <label>{{data.hzbtime}}</label> <br/> <br/>
  79. </div>
  80.   <div ng-show="data.connected">
  81. <h4>以下是websocket的客户端发消息到服务端,服务端再将该消息返回到客户端(页面)的例子</h4>
  82. <input type="text" ng-model="data.sendMessage" placeholder="请输入内容..." />
  83.     <button ng-click="send()" type="button">发送</button>
  84.     <br/>
  85.     <table>
  86.       <thead>
  87.         <tr>
  88.         <th>消息内容:</th>
  89.       </tr>
  90.        </thead>
  91.       <tbody>
  92.         <tr ng-repeat="messageContent in data.receivMessages">
  93.           <td>{{messageContent}}</td>
  94.       </tr>
  95.        </tbody>
  96.     </table>
  97. </div>
  98. </body>
  99. </html>

运行效果

没有点“连接”之前

点了“连接”之后

输入内容:点击发送

springboot+websocket示例的更多相关文章

  1. SpringBoot + WebSocket 开发笔记

    1. 服务端的实现,我尝试了两种方式: 第一种是用“@ServerEndPoint”注解来实现,实现简单: 第二种稍显麻烦,但是可以添加拦截器在WebSocket连接建立和断开前进行一些额外操作. 不 ...

  2. Springboot+Websocket+JWT实现的即时通讯模块

    场景 目前做了一个接口:邀请用户成为某课程的管理员,于是我感觉有能在用户被邀请之后能有个立马通知他本人的机(类似微博.朋友圈被点赞后就有立马能收到通知一样),于是就闲来没事搞了一套. ​ 涉及技术栈 ...

  3. 转:php使用websocket示例详解

    原文来自于:http://www.jb51.net/article/48019.htm 这篇文章主要介绍了php使用websocket示例,需要的朋友可以参考下   下面我画了一个图演示 client ...

  4. WebSocket 示例

    websocket应运而生 在WebSocket规范提出之前,开发人员若要实现带有即时通信.实时数据.订阅推送等功能的应用实时性较强的功能,经常会使用的解决方法是 Comet. Comet是一种服务器 ...

  5. SpringBoot+WebSocket

    SpringBoot+WebSocket 只需三个步骤 导入依赖 <dependency> <groupId>org.springframework.boot</grou ...

  6. springboot+websocket+sockjs进行消息推送【基于STOMP协议】

    springboot+websocket+sockjs进行消息推送[基于STOMP协议] WebSocket是在HTML5基础上单个TCP连接上进行全双工通讯的协议,只要浏览器和服务器进行一次握手,就 ...

  7. dubbo+zookeeper+springboot简单示例

    目录 dubbo+zookeeper+springboot简单示例 zookeeper安装使用 api子模块 生产者producer 消费者consumer @(目录) dubbo+zookeeper ...

  8. SpringBoot WebSocket STOMP 广播配置

    目录 1. 前言 2. STOMP协议 3. SpringBoot WebSocket集成 3.1 导入websocket包 3.2 配置WebSocket 3.3 对外暴露接口 4. 前端对接测试 ...

  9. Java Springboot webSocket简单实现,调接口推送消息到客户端socket

    Java Springboot webSocket简单实现,调接口推送消息到客户端socket 后台一般作为webSocket服务器,前台作为client.真实场景可能是后台程序在运行时(满足一定条件 ...

随机推荐

  1. 844. Backspace String Compare判断删除后的结果是否相等

    [抄题]: Given two strings S and T, return if they are equal when both are typed into empty text editor ...

  2. 实现Hibernate框架的CRUD

    1.创建Web项目HS_test如图所示: 2.创建数据库DBHSTest,在数据库中创建表Teacher,并插入数据 3.在Myeclipse中调出DB Brower视图 右键->New: 连 ...

  3. 纯css实现div中未知尺寸图片的垂直居中

    1.淘宝的方法 在曾经的"淘宝UED招聘"中有这样一道题目: “使用纯CSS实现未知尺寸的图片(但高宽都小于200px)在200px的正方形容器中水平和垂直居中.” 当然出题并不是 ...

  4. BTC和BCH 区别和联系?

    在比特币刚刚出现的时期,中本聪对区块的大小限制在1M.这种限制既保障性能较弱的个人电脑能够参与其中,同时也起到了防止攻击者让比特币网络超载的风险发生,毕竟那时系统还很脆弱.在1M的限制下,10分钟一个 ...

  5. Class 'com.mchange.v2.c3p0.ComboPooledDataSource' not found [config set

    解决方法: 修改maven <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</arti ...

  6. Linux netstat

    一.简介   二.语法   三.实例 1)查看TCP连接数 netstat -n | awk '/^tcp/ {++S[$NF]} END {for (a in S) print a, S[a]}'

  7. Ubuntu 软件包管理工具 dpkg, APT 的一些命令(转载)

    转载地址: http://www.dreamxu.com/ubuntu-package-dpkg-and-apt-commands/ dpkg dpkg 是由 Debian 开发的包管理系统,是一个比 ...

  8. RDMA的原理、传输与Verbs

    RDMA的原理.传输与Verbs   RDMA最早专属于infiniband架构.在网络融合的大趋势下出现的RoCE,使高速.超低延时.极低cpu使用率的RDMA得以部署在目前使用最广泛的以太网上.  ...

  9. javascript 高级程序设计 二

    这里我们直接进入主题: 在JS刚刚开始的时候,必须面临一个问题,那就是如何使的JS的加载和执行不会影响web核心语言HTML的展示效果,和HTML和谐共存. 在这个背景下<script>标 ...

  10. 调试程序时如何用syslog来打印信息

    转自:https://www.cnblogs.com/vigarbuaa/archive/2013/02/05/2892544.html Linux下C语言编程的-把程序输出信息加到系统日志里去关键词 ...