初入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 常见用法以及注意事项. ...
随机推荐
- 【BZOJ4388】JOI2012 invitation 堆+线段树+并查集(模拟Prim)
[BZOJ4388]JOI2012 invitation Description 澳洲猴举办了一场宴会,他想要邀请A个男生和B个女生参加,这A个男生从1到A编号,女生也从1到B编号.现在澳洲猴知道n组 ...
- Objective-C规范注释心得——同时兼容appledoc(docset、html)与doxygen(html、pdf)的文档生成
作者:zyl910 手工写文档是一件苦差事,幸好现在有从源码中抽取注释生成文档的专用工具.对于Objective-C来说,目前最好用的工具是appledoc和doxygen.可是这两种工具对于注释的要 ...
- 为什么 Java ArrayList.toArray(T[]) 方法的参数类型是 T 而不是 E ?
前两天给同事做 code review,感觉自己对 Java 的 Generics 掌握得不够好,便拿出 <Effective Java>1 这本书再看看相关的章节.在 Item 24:E ...
- 使用maven搭建SSM框架
使用maven搭建SSM框架,首先得准备好maven环境. 搭建maven环境 第一步:下载maven http://maven.apache.org/download.cgi 下载后解压就可以了. ...
- IOS And WCF 上传文件
IOS And WCF Story 研究IOS上传到WCF图片的小功能,WCF实现服务端的文件上传的例子很多,单独实现IOS发送图片的例子也很多,但是两个结合起来的就很少了. 可以通过base64来上 ...
- Storm-源码分析-Topology Submit-Executor-mk-threads
对于executor thread是整个storm最为核心的代码, 因为在这个thread里面真正完成了大部分工作, 而其他的如supervisor,worker都是封装调用. 对于executor的 ...
- Eclipse 介绍
设置背景的插件: Darkest Dark Theme 添加 properties 插件: Properties Editor Git 插件: Egit 常用快捷键 command + 1 : 代码提 ...
- 初识python(二)
初识python(二) 1.变量 变量:把程序运行的中间结果临时的存在内存里,以便后续的代码调用. 1.1 声明变量: #!/usr/bin/env python # -*- coding: utf- ...
- CNI bridge 插件实现代码分析
对于每个CNI 插件在执行函数cmdAdd之前的操作是完全一样的,即从环境变量和标准输入内读取配置.这在http://www.cnblogs.com/YaoDD/p/6410725.html这篇博文里 ...
- Linux基础整理 + 注释
1.Linux的常用命令: ls 显示当前文件夹目录 ll -->详细信息 ls -a 显示所有文件 ls -lhSr w 查看登录的帐号,还可以查看cpu负载情况,who am i ,who ...