初入spring boot(五 )websocket
一、广播式
广播式即服务端有消息时,会将消息发送给所有连接了当前endpoint的浏览器
1.配置websocket,需要在配置类上使用@EnableWebSocketMessageBroker开启websocket支持,并通过继承AbstractWebSocketMessageBrokerConfigurer类,重写其方法来配置websocket
@Configuration
@EnableWebSocketMessageBroker //1
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{ @Override
public void registerStompEndpoints(StompEndpointRegistry registry) { //2
registry.addEndpoint("/endpointWisely").withSockJS();
registry.addEndpoint("/endpointChat").withSockJS();//3
} @Override
public void configureMessageBroker(MessageBrokerRegistry registry) { //4
registry.enableSimpleBroker("/queue","/topic"); //5
} }
1. 通过@EnableWebSocketMessageBroker注解开启使用STOMP协议来传输基于代理(message broker)的消息,这时控制器支持使用@MessageMapping,就像使用@RequestMapping一样。
2. 注册STOMP协议的节点(endpoint),并映射的指定的URL
3. 注册一个STOMP的endpoint,并指定使用SockJS协议
4. 配置消息代理(Message Broker)
5. 广播式配置一个/topic消息代理
@Controller
public class WsController { @MessageMapping("/welcome")
@SendTo("/topic/getResponse")
public WiselyResponse say(WiselyMessage message) throws Exception {
Thread.sleep(3000);
return new WiselyResponse("Welcome, " + message.getName() + "!");
} @Autowired
private SimpMessagingTemplate messagingTemplate;// @MessageMapping("/chat")
public void handleChat(Principal principal, String msg) { //
if (principal.getName().equals("wyf")) {//
messagingTemplate.convertAndSendToUser("wisely",
"/queue/notifications", principal.getName() + "-send:"
+ msg);
} else {
messagingTemplate.convertAndSendToUser("wyf",
"/queue/notifications", principal.getName() + "-send:"
+ msg);
}
}
}
1. 当浏览器向服务端发送请求时,通过@MessageMapping("/welcome")映射/welcome这个地址,类似于@RequestMapping
2. 当服务端有消息时,会对订阅了@SendTo中的路径的浏览器发送消息
2. 脚本代码如下:ws.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Spring Boot+WebSocket+广播式</title> </head>
<body onload="disconnect()">
<noscript><h2 style="color: #ff0000">貌似你的浏览器不支持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" />
<button id="sendName" onclick="sendName();">发送</button>
<p id="response"></p>
</div>
</div>
<script th:src="@{sockjs.min.js}"></script>
<script th:src="@{stomp.min.js}"></script>
<script th:src="@{jquery.js}"></script>
<script type="text/javascript">
var stompClient = null; function setConnected(connected) {
document.getElementById('connect').disabled = connected;
document.getElementById('disconnect').disabled = !connected;
document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
$('#response').html();
} function connect() {
var socket = new SockJS('/endpointWisely'); //1
stompClient = Stomp.over(socket); //2
stompClient.connect({}, function(frame) { //3
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/getResponse', function(respnose){ //4
showResponse(JSON.parse(respnose.body).responseMessage);
});
});
} function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
} function sendName() {
var name = $('#name').val(); //5 stompClient.send("/welcome", {}, JSON.stringify({ 'name': name }));
} function showResponse(message) {
var response = $("#response");
response.html(message);
}
</script>
</body>
</html> 1. 连接SockJs的endpoint名称为“/endpointWisely”
2. 使用STOMP子协议的websocket客户端
3. 连接websocket服务端
4. 通过stompClient.subscribe订阅/topic/getResponse目标发送的消息,这是由@SendTo定义的
5. 通过stompClient.send向/welcome目标发送消息,这是由@MessageMapping定义的
3. 配置viewController
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter{ @Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/ws").setViewName("/ws");
registry.addViewController("/login").setViewName("/login");
registry.addViewController("/chat").setViewName("/chat");
} }
初入spring boot(五 )websocket的更多相关文章
- 初入spring boot(八 )Spring Data REST
1. 什么是Spring Data REST Spring Data JPA是基于Spring Data 的Repository之上,可以将Repository自动输出为REST资源.目前Spring ...
- 初入spring boot(七 )Spring Data JPA
Spring Data JPA通过提供基于JPA的Repository极大地减少JPA作为数据访问方案的代码量. 1.定义数据访问层 使用Spring Data JPA建立数据访问层十分简单,只需定义 ...
- 初入spring boot(四 )web项目
1. 模板引擎 spring boot提供了大量的模板引擎,包括FreeMark.Groovy.Thymeleaf.Velocity等,但spring boot中推荐用Thymeleaf,因为Thym ...
- 【websocket】spring boot 集成 websocket 的四种方式
集成 websocket 的四种方案 1. 原生注解 pom.xml <dependency> <groupId>org.springframework.boot</gr ...
- spring boot 集成 websocket 实现消息主动推送
spring boot 集成 websocket 实现消息主动 前言 http协议是无状态协议,每次请求都不知道前面发生了什么,而且只可以由浏览器端请求服务器端,而不能由服务器去主动通知浏览器端,是单 ...
- Spring Boot之WebSocket
一.项目说明 1.项目地址:https://github.com/hqzmss/test01-springboot-websocket.git 2.IDE:IntelliJ IDEA 2018.1.1 ...
- Spring Boot 集成 WebSocket 实现服务端推送消息到客户端
假设有这样一个场景:服务端的资源经常在更新,客户端需要尽量及时地了解到这些更新发生后展示给用户,如果是 HTTP 1.1,通常会开启 ajax 请求询问服务端是否有更新,通过定时器反复轮询服务端响应的 ...
- spring boot(五):spring data jpa的使用
在上篇文章springboot(二):web综合开发中简单介绍了一下spring data jpa的基础性使用,这篇文章将更加全面的介绍spring data jpa 常见用法以及注意事项 使用spr ...
- Spring Boot(五):Spring Boot Jpa 的使用
在上篇文章Spring Boot(二):Web 综合开发中简单介绍了一下 Spring Boot Jpa 的基础性使用,这篇文章将更加全面的介绍 Spring Boot Jpa 常见用法以及注意事项. ...
随机推荐
- Castle 整合.NET Remoting
今天研究了一下Castle的Remoting Facility.记录如下: 微软以前使用COM/DCOM的技术来处理分布式系统架构,通过Client端的Proxy代理程序来呼叫远程Server机器上的 ...
- 3162 抄书问题(划分dp)
3162 抄书问题 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 钻石 Diamond 题解 查看运行结果 题目描述 Description 现在要把M本有顺序的书分给K个人复制( ...
- InetAddress类和InetSocketAddress的使用
一简介 InetAddress是Java对IP地址的封装,代表互联网协议(IP)地址:InetAddress对象的获取只能通过静态方法,比如根据主机名获取主机的ip地址封装对象: ? 1 InetAd ...
- Flutter入门之有状态组件
StatefulComponent使用方法入门 在上一篇Flutter入门之无状态组件中我们讲到了无状态组件,所谓的无状态组件指的就是其内部的状态是来自其父组件并使用final类型的变量来存储,当组件 ...
- iOS接收远程通知响应方法
点击 iOS 接收远程推送主要牵扯到的方法有以下五种 (1) - (BOOL)application:(UIApplication *)application didFinishLaunchingWi ...
- 【Python之路】第十二篇--JavaScript
JavaScript 历史 1992年Nombas开发出C-minus-minus(C--)的嵌入式脚本语言(最初绑定在CEnvi软件中).后将其改名ScriptEase.(客户端执行的语言) Net ...
- django博客项目2.建立 Django 博客应用
建立博客应用 我们已经建立了 Django 博客的项目工程,并且成功地运行了它.不过到目前为止这一切都还只是 Django 为我们创建的项目初始内容,Django 不可能为我们初始化生成博客代码,这些 ...
- django博客项目1.环境搭建
安装 Python Windows 下安装 Python 非常简单,去 Python 官方网站找到 Python 3 的下载地址,根据你的系统选择 32 位或者 64 位的安装包,下载好后双击安装即可 ...
- mysql多条更新
最近在完成MySql项目集成的情况下,需要增加批量更新的功能,根据网上的资料整理了一下,很好用,都测试过,可以直接使用. mysql 批量更新共有以下四种办法 1..replace into 批量更新 ...
- python数据类型一(重点是字符串的各种操作)
一.python基本数据类型 1,int,整数,主要用来进行数学运算 2,bool,布尔类型,判断真假,True,False 3,str,字符串,可以保存少量数据并进行相应的操作(未来使用频率最高的一 ...