初入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 常见用法以及注意事项. ...
随机推荐
- [多媒体] m3u8简介
m3u8简介 简介:https://www.jianshu.com/p/426425cad08a RFC:https://tools.ietf.org/html/rfc8216 原理:将视频或音频流分 ...
- bzoj2656
题目链接:传送门 题目大意:已知 a0=0:a1=1: n为偶数 an=a(n/2):n为基数 an=a(n/2)+a(n/2+1): 题目思路:因为n过大,所以要用java高精度,还有最多20组数据 ...
- swift UITextField
var textField = UITextField(frame: CGRectMake(10,160,200,30)) //设置边框样式为圆角矩形 textField.borderStyle = ...
- (转) RabbitMQ学习之延时队列
http://blog.csdn.net/zhu_tianwei/article/details/53563311 在实际的业务中我们会遇见生产者产生的消息,不立即消费,而是延时一段时间在消费.Rab ...
- Maven 整合SSH框架之pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...
- Java 其他对象的 API
System 类 (java.lang 包下) 该类中的方法和属性都是静态的. 常见方法 // 1, 获取当前时间的毫秒值 long currentTimeMillis(); // 2, 获取系统的属 ...
- django博客项目6:Django Admin 后台发布文章
在此之前我们完成了 Django 博客首页视图的编写,我们希望首页展示发布的博客文章列表,但是它却抱怨:暂时还没有发布的文章!如它所言,我们确实还没有发布任何文章,本节我们将使用 Django 自带的 ...
- OpenSSL和https原理
https原理: 浏览器请求服务端的公钥证书,server将注冊的证书发送给client. client向办法机构验证证书的合法性,证书 包含公钥,server网址及一些信息. 验证完成,client ...
- 利用Docker快速部署Oracle环境
工作中需要频繁使用Oracle环境,但是每次搭建起来比较消耗时间,本想通过虚拟机模板的方式来快速安装oracle vm,但是每次改ip等环境也很耗时,因此想到docker中有没有已经做好的images ...
- T25健身视频全集+课表
http://jianfei.39.net/thread-3639251-1.html T25健身视频全集+课表 强度适中 不伤膝盖! [复制链接] zytttt 主题 好友 ...