目录结构

pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.web.socket</groupId>
  5. <artifactId>websocket</artifactId>
  6. <packaging>war</packaging>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <name>websocket Maven Webapp</name>
  9. <url>http://maven.apache.org</url>
  10. <parent>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-parent</artifactId>
  13. <version>2.0.0.RELEASE</version>
  14. </parent>
  15. <properties>
  16. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  17. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  18. <java.version>1.8</java.version>
  19. </properties>
  20. <dependencies>
  21. <dependency>
  22. <groupId>org.springframework</groupId>
  23. <artifactId>spring-messaging</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter</artifactId>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-web</artifactId>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-starter-websocket</artifactId>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.springframework.boot</groupId>
  39. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  40. </dependency>
  41. <dependency>
  42. <groupId>javax.servlet</groupId>
  43. <artifactId>javax.servlet-api</artifactId>
  44. <scope>provided</scope>
  45. </dependency>
  46. <dependency>
  47. <groupId>junit</groupId>
  48. <artifactId>junit</artifactId>
  49. <scope>test</scope>
  50. </dependency>
  51. </dependencies>
  52. <build>
  53. <finalName>websocket</finalName>
  54. </build>
  55. </project>

WebSocketConfig.java

  1. package com.web.socket.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. @Configuration
  10. //表示开启使用STOMP协议来传输基于代理的消息,Broker就是代理的意思。
  11. @EnableWebSocketMessageBroker
  12. public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{
  13. @Override
  14. public void configureMessageBroker(MessageBrokerRegistry registry) {
  15. registry.enableSimpleBroker(AppConfig.BROKER);
  16. }
  17. @Override
  18. public void registerStompEndpoints(StompEndpointRegistry registry) {
  19. //这一行代码用来注册STOMP协议节点,同时指定使用SockJS协议。
  20. registry.addEndpoint(AppConfig.ENDPOINT).withSockJS();
  21. }
  22. }

AppConfig.java

  1. package com.web.socket.config;
  2.  
  3. public class AppConfig {
  4. /**
  5. * 被订阅的频道
  6. */
  7. public static final String SUBSCRIBE = "/topic/message";
  8. /**
  9. * stomp节点
  10. */
  11. public static final String ENDPOINT = "/endpointYC";
  12. /**
  13. * 消息代理
  14. */
  15. public static final String BROKER = "/topic";
  16. }

WebSocketController.java

  1. package com.web.socket.controller;
  2.  
  3. import java.io.IOException;
  4.  
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.messaging.handler.annotation.MessageMapping;
  7. import org.springframework.messaging.handler.annotation.SendTo;
  8. import org.springframework.messaging.simp.SimpMessagingTemplate;
  9. import org.springframework.stereotype.Controller;
  10. import org.springframework.web.bind.annotation.PostMapping;
  11. import org.springframework.web.bind.annotation.RequestBody;
  12. import org.springframework.web.bind.annotation.ResponseBody;
  13.  
  14. import com.web.socket.config.AppConfig;
  15. import com.web.socket.entity.RequestMessage;
  16. import com.web.socket.entity.ResponseMessage;
  17.  
  18. @Controller
  19. public class WsController {
  20. @Autowired
  21. private SimpMessagingTemplate simpMessagingTemplate;
  22.  
  23. /**
  24. * @title websocket产生消息,并推送
  25. * @param message
  26. * @return
  27. */
  28. @MessageMapping("/ws")//和@RequestMapping类似
  29. @SendTo(AppConfig.SUBSCRIBE)//当服务器有消息需要推送的时候,会对订阅了@SendTo中路径的浏览器发送消息
  30. public ResponseMessage say(RequestMessage message) {
  31. System.out.println(message.getName());
  32. return new ResponseMessage(message.toString());
  33. }
  34.  
  35. /**
  36. * @title http请求产生消息,并推送
  37. * @param message
  38. * @return
  39. * @throws IOException
  40. */
  41. @PostMapping("/http")
  42. @ResponseBody
  43. public String send(@RequestBody RequestMessage message) throws IOException {
  44. System.out.println(message.getName());
  45. simpMessagingTemplate.convertAndSend(AppConfig.SUBSCRIBE,new ResponseMessage(message.toString()) );
  46. return "success";
  47. }
  48. }

ws.html

  1. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  2. <head>
  3. <meta charset="UTF-8"/>
  4. <title>广播式WebSocket</title>
  5. <script th:src="@{static/js/sockjs.min.js}"></script>
  6. <script th:src="@{static/js/stomp.js}"></script>
  7. <script th:src="@{static/js/jquery-3.3.1.min.js}"></script>
  8. </head>
  9. <body onload="disconnect()">
  10. <noscript><h2 style="color: #e80b0a;">Sorry,浏览器不支持WebSocket</h2></noscript>
  11. <div>
  12. <div>
  13. <button id="connect" onclick="connect();">连接</button>
  14. <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
  15. </div>
  16. <div id="conversationDiv">
  17. <label>名字</label><input type="text" id="name"/>
  18. <label>内容</label><input type="text" id="content"/>
  19. <button id="sendName" onclick="sendName();">发送</button>
  20. <p id="response"></p>
  21. </div>
  22. </div>
  23. <script type="text/javascript">
  24. var stompClient = null;
  25. /**
  26. * 设置组件样式
  27. * @param {Object} connected
  28. */
  29. function setConnected(connected) {
  30. document.getElementById("connect").disabled = connected;
  31. document.getElementById("disconnect").disabled = !connected;
  32. document.getElementById("conversationDiv").style.visibility = connected ? 'visible' : 'hidden';
  33. $("#response").html();
  34. }
  35. /**
  36. * 创建socket连接
  37. */
  38. function connect() {
  39. //链接SockJS 的endpoint 名称为endpointSang
  40. var socket = new SockJS('/endpointYC');
  41. //使用stomp子协议的WebSocket 客户端
  42. stompClient = Stomp.over(socket);
  43. //链接Web Socket的服务端。
  44. stompClient.connect({}, function (frame) {
  45. setConnected(true);
  46. //订阅/topic/message频道,并对收到信息进行处理
  47. stompClient.subscribe('/topic/message', function (response) {
  48. showResponse(JSON.parse(response.body).responseMessage);
  49. })
  50. });
  51. }
  52. /**
  53. * 断开连接
  54. */
  55. function disconnect() {
  56. if (stompClient != null) {
  57. stompClient.disconnect();
  58. }
  59. setConnected(false);
  60. }
  61. /**
  62. * 向服务器发送消息
  63. */
  64. function sendName() {
  65. var name = $('#name').val();
  66. var content = $('#content').val();
  67. stompClient.send("/ws", {}, JSON.stringify({'name': name,'content':content,'date':new Date()}));
  68. }
  69. /**
  70. * 替换文本
  71. * @param {Object} message 服务器返回数据
  72. */
  73. function showResponse(message) {
  74. $("#response").html(message);
  75. }
  76. </script>
  77. </body>
  78. </html>

使用浏览器访http://127.0.0.1/ws就可以测试websocket方式广播。

在有socket连接的情况下,访问http://127.0.0.1/http,并使用post方式请求,就可以在ws页面看到发送的数据了。

springboot + websocket + spring-messaging实现服务器向浏览器广播式的更多相关文章

  1. Spring之WebSocket网页聊天以及服务器推送

    Spring之WebSocket网页聊天以及服务器推送 转自:http://www.xdemo.org/spring-websocket-comet/ /Springframework /Spring ...

  2. SpringBoot集成websocket(Spring方式)

    SpringWebSocketConfig配置 package com.meeno.chemical.socket.task.config; import com.meeno.chemical.soc ...

  3. springboot websocket 一篇足够了

    什么是WebSocket WebSocket是一种在单个TCP连接上进行全双工通信的协议 … 为什么要实现握手监控管理 如果说,连接随意创建,不管的话,会存在错误,broken pipe 表面看单纯报 ...

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

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

  5. springBoot -webSocket 基于STOMP协议交互

    浅谈WebSocket WebSocket是在HTML5基础上单个TCP连接上进行全双工通讯的协议,只要浏览器和服务器进行一次握手,就可以建立一条快速通道,两者就可以实现数据互传了.说白了,就是打破了 ...

  6. springboot websocket集群(stomp协议)连接时候传递参数

    最近在公司项目中接到个需求.就是后台跟前端浏览器要保持长连接,后台主动往前台推数据. 网上查了下,websocket stomp协议处理这个很简单.尤其是跟springboot 集成. 但是由于开始是 ...

  7. springboot websocket 简单入门

    在没有WebSocket时,大多时候我们在处理服务端主动给浏览器推送消息都是非常麻烦,且有很多弊端,如: 1.Ajax轮循 优点:客户端很容易实现良好的错误处理系统和超时管理,实现成本与Ajax轮询的 ...

  8. SpringBoot WebSocket STOMP 广播配置

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

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

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

随机推荐

  1. python基础——字符串、编码、格式化

    1.三种编码:ascii Unicode utf8 2.字符串和编码数字的两个函数:ord(字符转数字ord(‘A’)=65)和 chr(数字转字符chr(65)=A) 3.bytes存储编码,记住两 ...

  2. Js计算时间差,天数,小时数,余数

    var begintime_ms = Date.parse(new Date(begintime.replace(/-/g, "/"))); //begintime 为开始时间 v ...

  3. 51Nod1553 周期串查询 字符串 哈希 线段树

    原文链接https://www.cnblogs.com/zhouzhendong/p/51Nod1553.html 题目传送门 - 51Nod1553 题意 有一个串只包含数字字符.串的长度为n,下标 ...

  4. Codeforces 1000G Two-Paths 树形动态规划 LCA

    原文链接https://www.cnblogs.com/zhouzhendong/p/9246484.html 题目传送门 - Codeforces 1000G Two-Paths 题意 给定一棵有 ...

  5. HDU5692 Snacks DFS序 线段树

    去博客园看该题解 题目 HDU5692 Snacks Problem Description 百度科技园内有n个零食机,零食机之间通过n−1条路相互连通.每个零食机都有一个值v,表示为小度熊提供零食的 ...

  6. springmvc基础使用配置

    前言 本案例是在idea编辑器下,maven管理项目的前提下. 步骤 1.新建maven项目 2.配置web.xml <?xml version="1.0" encoding ...

  7. Shiro笔记(一)Shiro整体介绍

    介绍:是一个java的安全(权限)框架 可以完成的功能:认证登录(Authentication).授权(Authorization).加密(cryptography).会话管理(session man ...

  8. linux同步Internet时间

    输入ntpdate time.nist.gov同步网络时间 如果未安装:yum install ntpdate 结果:3 Jun 15:42:39 ntpdate[4721]: adjust time ...

  9. 多媒体开发(8):调试FFmpeg

    编译FFmpeg得到二进制文件,之后就是对二进制库的调用,这时FFmpeg就像一个黑盒子.作为程序员,难道不想研究一下FFmpeg的具体实现?比如是怎么拿到歌曲信息的.怎么解码的.怎么推流的,等等. ...

  10. 从函数式编程到Ramda函数库(二)

    Ramda 基本的数据结构都是原生 JavaScript 对象,我们常用的集合是 JavaScript 的数组.Ramda 还保留了许多其他原生 JavaScript 特性,例如,函数是具有属性的对象 ...