springboot + websocket + spring-messaging实现服务器向浏览器广播式
目录结构
pom.xml
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.web.socket</groupId>
- <artifactId>websocket</artifactId>
- <packaging>war</packaging>
- <version>0.0.1-SNAPSHOT</version>
- <name>websocket Maven Webapp</name>
- <url>http://maven.apache.org</url>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.0.0.RELEASE</version>
- </parent>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <java.version>1.8</java.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-messaging</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-websocket</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-thymeleaf</artifactId>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>javax.servlet-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <build>
- <finalName>websocket</finalName>
- </build>
- </project>
WebSocketConfig.java
- package com.web.socket.config;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.messaging.simp.config.MessageBrokerRegistry;
- import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
- import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
- import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
- @Configuration
- //表示开启使用STOMP协议来传输基于代理的消息,Broker就是代理的意思。
- @EnableWebSocketMessageBroker
- public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{
- @Override
- public void configureMessageBroker(MessageBrokerRegistry registry) {
- registry.enableSimpleBroker(AppConfig.BROKER);
- }
- @Override
- public void registerStompEndpoints(StompEndpointRegistry registry) {
- //这一行代码用来注册STOMP协议节点,同时指定使用SockJS协议。
- registry.addEndpoint(AppConfig.ENDPOINT).withSockJS();
- }
- }
AppConfig.java
- package com.web.socket.config;
- public class AppConfig {
- /**
- * 被订阅的频道
- */
- public static final String SUBSCRIBE = "/topic/message";
- /**
- * stomp节点
- */
- public static final String ENDPOINT = "/endpointYC";
- /**
- * 消息代理
- */
- public static final String BROKER = "/topic";
- }
WebSocketController.java
- package com.web.socket.controller;
- import java.io.IOException;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.messaging.handler.annotation.MessageMapping;
- import org.springframework.messaging.handler.annotation.SendTo;
- import org.springframework.messaging.simp.SimpMessagingTemplate;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.ResponseBody;
- import com.web.socket.config.AppConfig;
- import com.web.socket.entity.RequestMessage;
- import com.web.socket.entity.ResponseMessage;
- @Controller
- public class WsController {
- @Autowired
- private SimpMessagingTemplate simpMessagingTemplate;
- /**
- * @title websocket产生消息,并推送
- * @param message
- * @return
- */
- @MessageMapping("/ws")//和@RequestMapping类似
- @SendTo(AppConfig.SUBSCRIBE)//当服务器有消息需要推送的时候,会对订阅了@SendTo中路径的浏览器发送消息
- public ResponseMessage say(RequestMessage message) {
- System.out.println(message.getName());
- return new ResponseMessage(message.toString());
- }
- /**
- * @title http请求产生消息,并推送
- * @param message
- * @return
- * @throws IOException
- */
- @PostMapping("/http")
- @ResponseBody
- public String send(@RequestBody RequestMessage message) throws IOException {
- System.out.println(message.getName());
- simpMessagingTemplate.convertAndSend(AppConfig.SUBSCRIBE,new ResponseMessage(message.toString()) );
- return "success";
- }
- }
ws.html
- <html lang="en" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8"/>
- <title>广播式WebSocket</title>
- <script th:src="@{static/js/sockjs.min.js}"></script>
- <script th:src="@{static/js/stomp.js}"></script>
- <script th:src="@{static/js/jquery-3.3.1.min.js}"></script>
- </head>
- <body onload="disconnect()">
- <noscript><h2 style="color: #e80b0a;">Sorry,浏览器不支持WebSocket</h2></noscript>
- <div>
- <div>
- <button id="connect" onclick="connect();">连接</button>
- <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
- </div>
- <div id="conversationDiv">
- <label>名字</label><input type="text" id="name"/>
- <label>内容</label><input type="text" id="content"/>
- <button id="sendName" onclick="sendName();">发送</button>
- <p id="response"></p>
- </div>
- </div>
- <script type="text/javascript">
- var stompClient = null;
- /**
- * 设置组件样式
- * @param {Object} connected
- */
- function setConnected(connected) {
- document.getElementById("connect").disabled = connected;
- document.getElementById("disconnect").disabled = !connected;
- document.getElementById("conversationDiv").style.visibility = connected ? 'visible' : 'hidden';
- $("#response").html();
- }
- /**
- * 创建socket连接
- */
- function connect() {
- //链接SockJS 的endpoint 名称为endpointSang
- var socket = new SockJS('/endpointYC');
- //使用stomp子协议的WebSocket 客户端
- stompClient = Stomp.over(socket);
- //链接Web Socket的服务端。
- stompClient.connect({}, function (frame) {
- setConnected(true);
- //订阅/topic/message频道,并对收到信息进行处理
- stompClient.subscribe('/topic/message', function (response) {
- showResponse(JSON.parse(response.body).responseMessage);
- })
- });
- }
- /**
- * 断开连接
- */
- function disconnect() {
- if (stompClient != null) {
- stompClient.disconnect();
- }
- setConnected(false);
- }
- /**
- * 向服务器发送消息
- */
- function sendName() {
- var name = $('#name').val();
- var content = $('#content').val();
- stompClient.send("/ws", {}, JSON.stringify({'name': name,'content':content,'date':new Date()}));
- }
- /**
- * 替换文本
- * @param {Object} message 服务器返回数据
- */
- function showResponse(message) {
- $("#response").html(message);
- }
- </script>
- </body>
- </html>
使用浏览器访http://127.0.0.1/ws就可以测试websocket方式广播。
在有socket连接的情况下,访问http://127.0.0.1/http,并使用post方式请求,就可以在ws页面看到发送的数据了。
springboot + websocket + spring-messaging实现服务器向浏览器广播式的更多相关文章
- Spring之WebSocket网页聊天以及服务器推送
Spring之WebSocket网页聊天以及服务器推送 转自:http://www.xdemo.org/spring-websocket-comet/ /Springframework /Spring ...
- SpringBoot集成websocket(Spring方式)
SpringWebSocketConfig配置 package com.meeno.chemical.socket.task.config; import com.meeno.chemical.soc ...
- springboot websocket 一篇足够了
什么是WebSocket WebSocket是一种在单个TCP连接上进行全双工通信的协议 … 为什么要实现握手监控管理 如果说,连接随意创建,不管的话,会存在错误,broken pipe 表面看单纯报 ...
- springboot+websocket+sockjs进行消息推送【基于STOMP协议】
springboot+websocket+sockjs进行消息推送[基于STOMP协议] WebSocket是在HTML5基础上单个TCP连接上进行全双工通讯的协议,只要浏览器和服务器进行一次握手,就 ...
- springBoot -webSocket 基于STOMP协议交互
浅谈WebSocket WebSocket是在HTML5基础上单个TCP连接上进行全双工通讯的协议,只要浏览器和服务器进行一次握手,就可以建立一条快速通道,两者就可以实现数据互传了.说白了,就是打破了 ...
- springboot websocket集群(stomp协议)连接时候传递参数
最近在公司项目中接到个需求.就是后台跟前端浏览器要保持长连接,后台主动往前台推数据. 网上查了下,websocket stomp协议处理这个很简单.尤其是跟springboot 集成. 但是由于开始是 ...
- springboot websocket 简单入门
在没有WebSocket时,大多时候我们在处理服务端主动给浏览器推送消息都是非常麻烦,且有很多弊端,如: 1.Ajax轮循 优点:客户端很容易实现良好的错误处理系统和超时管理,实现成本与Ajax轮询的 ...
- SpringBoot WebSocket STOMP 广播配置
目录 1. 前言 2. STOMP协议 3. SpringBoot WebSocket集成 3.1 导入websocket包 3.2 配置WebSocket 3.3 对外暴露接口 4. 前端对接测试 ...
- Springboot+Websocket+JWT实现的即时通讯模块
场景 目前做了一个接口:邀请用户成为某课程的管理员,于是我感觉有能在用户被邀请之后能有个立马通知他本人的机(类似微博.朋友圈被点赞后就有立马能收到通知一样),于是就闲来没事搞了一套. 涉及技术栈 ...
随机推荐
- python基础——字符串、编码、格式化
1.三种编码:ascii Unicode utf8 2.字符串和编码数字的两个函数:ord(字符转数字ord(‘A’)=65)和 chr(数字转字符chr(65)=A) 3.bytes存储编码,记住两 ...
- Js计算时间差,天数,小时数,余数
var begintime_ms = Date.parse(new Date(begintime.replace(/-/g, "/"))); //begintime 为开始时间 v ...
- 51Nod1553 周期串查询 字符串 哈希 线段树
原文链接https://www.cnblogs.com/zhouzhendong/p/51Nod1553.html 题目传送门 - 51Nod1553 题意 有一个串只包含数字字符.串的长度为n,下标 ...
- Codeforces 1000G Two-Paths 树形动态规划 LCA
原文链接https://www.cnblogs.com/zhouzhendong/p/9246484.html 题目传送门 - Codeforces 1000G Two-Paths 题意 给定一棵有 ...
- HDU5692 Snacks DFS序 线段树
去博客园看该题解 题目 HDU5692 Snacks Problem Description 百度科技园内有n个零食机,零食机之间通过n−1条路相互连通.每个零食机都有一个值v,表示为小度熊提供零食的 ...
- springmvc基础使用配置
前言 本案例是在idea编辑器下,maven管理项目的前提下. 步骤 1.新建maven项目 2.配置web.xml <?xml version="1.0" encoding ...
- Shiro笔记(一)Shiro整体介绍
介绍:是一个java的安全(权限)框架 可以完成的功能:认证登录(Authentication).授权(Authorization).加密(cryptography).会话管理(session man ...
- linux同步Internet时间
输入ntpdate time.nist.gov同步网络时间 如果未安装:yum install ntpdate 结果:3 Jun 15:42:39 ntpdate[4721]: adjust time ...
- 多媒体开发(8):调试FFmpeg
编译FFmpeg得到二进制文件,之后就是对二进制库的调用,这时FFmpeg就像一个黑盒子.作为程序员,难道不想研究一下FFmpeg的具体实现?比如是怎么拿到歌曲信息的.怎么解码的.怎么推流的,等等. ...
- 从函数式编程到Ramda函数库(二)
Ramda 基本的数据结构都是原生 JavaScript 对象,我们常用的集合是 JavaScript 的数组.Ramda 还保留了许多其他原生 JavaScript 特性,例如,函数是具有属性的对象 ...