SpringBoot---Web开发---WebSocket
【广播式】
1、
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.an</groupId>
<artifactId>springbootwebsocket</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springbootwebsocket</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</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-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

2、application.properties
#Tomcat
server.tomcat.uri-encoding=utf-8
server.tomcat.max-threads=1000
server.tomcat.min-spare-threads=100
server.port=8080
server.servlet.context-path=/ #Thymeleaf
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.servlet.content-type=text/html spring.resources.static-locations=classpath:/static/
3、ws.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>SpringBoot+WebSocket【广播模式】</title>
</head>
<body onload="disconnect();">
<noscript>
<h2>您的浏览器不支持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="@{stomp.js}"></script>
<script th:src="@{sockjs.js}"></script>
<script th:src="@{jquery.min.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");
stompClient=Stomp.over(socket);
stompClient.connect({},function (frame) {
setConnected(true);
console.log('Connected'+frame);
//通过stompClient.subscribe订阅 /topic/getResponse目标(在Controller的@SendTo中定义) 发送的消息
stompClient.subscribe('/topic/getResponse',function (response) {
showResponse(JSON.parse(response.body).responseMessage);
});
});
} function disconnect() {
if (stompClient!=null){
stompClient.disconnect();
}
setConnected(false);
console.log('DisConnected');
} function sendName() {
var name=$("#name").val();
//通过stompClient.send向 /welcome目标(在Controller的@MessageMapping中定义) 发送消息
stompClient.send("/welcome",{},JSON.stringify({'name':name}));
} function showResponse(message) {
var response=$("#response");
response.html(message);
}
</script>
</body>
</html>
4、
package com.an.springbootwebsocket; /**
* 浏览器向服务器发送消息,用此类接受
*/
public class WiselyMessage { private String name; public String getName() {
return name;
}
}
5、
package com.an.springbootwebsocket; /**
* 服务器向浏览器发送的消息
*/
public class WiselyResponse { private String responseMessage; public WiselyResponse(String responseMessage){
this.responseMessage=responseMessage;
} public String getResponseMessage() {
return responseMessage;
}
}
6、
package com.an.springbootwebsocket; 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; /**
* 通过@EnableWebSocketMessageBroker开启使用STOMP协议来传输基于代理的消息;
* Controller使用@MessageMapping,类似于@RequestMapping
*/
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { /**
* 注册STOMP协议的节点,并映射指定的URL
* @param registry
*/
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
//注册一个STOMP协议的endpoint,并指定使用SockJS协议
registry.addEndpoint("/endpointWisely").withSockJS();
} /**
* 配置消息代理
* @param registry
*/
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
//广播式应配置一个/topic消息代理
registry.enableSimpleBroker("/topic");
}
}
7、
package com.an.springbootwebsocket; import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/ws").setViewName("/ws");
}
}
8、
package com.an.springbootwebsocket; import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller; @Controller
public class WsController { /**
* 1、当浏览器向服务器发送请求时,通过@MessageMapping映射/welcome地址;
* 2、当服务器有消息时,会对订阅了@SendTo中的路径的浏览器发送消息
* @param wiselyMessage
* @return
*/
@MessageMapping(value = "/welcome")
@SendTo(value = "/topic/getResponse")
public WiselyResponse say(WiselyMessage wiselyMessage){
return new WiselyResponse(wiselyMessage.getName());
}
}
SpringBoot---Web开发---WebSocket的更多相关文章
- SpringBoot Web开发(5) 开发页面国际化+登录拦截
SpringBoot Web开发(5) 开发页面国际化+登录拦截 一.页面国际化 页面国际化目的:根据浏览器语言设置的信息对页面信息进行切换,或者用户点击链接自行对页面语言信息进行切换. **效果演示 ...
- SpringBoot Web开发(4) Thymeleaf模板与freemaker
SpringBoot Web开发(4) Thymeleaf模板与freemaker 一.模板引擎 常用得模板引擎有JSP.Velocity.Freemarker.Thymeleaf SpringBoo ...
- 【SpringBoot】SpringBoot Web开发(八)
本周介绍SpringBoot项目Web开发的项目内容,及常用的CRUD操作,阅读本章前请阅读[SpringBoot]SpringBoot与Thymeleaf模版(六)的相关内容 Web开发 项目搭建 ...
- springboot web开发【转】【补】
pom.xml引入webjars的官网 https://www.webjars.org/ https://www.thymeleaf.org/doc/tutorials/3.0/usingthymel ...
- SpringBoot(四): SpringBoot web开发 SpringBoot使用jsp
1.在SpringBoot中使用jsp,需要在pom.xml文件中添加依赖 <!--引入Spring Boot内嵌的Tomcat对JSP的解析包--> <dependency> ...
- Spring-boot -Web开发
1).创建SpringBoot应用,选中我们需要的模块: 2).SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来 3).自己编写业务代码: 文件名的功能 x ...
- SpringBoot Web开发(3) WebMvcConfigurerAdapter过期替代方案
springboot2.0中 WebMvcConfigurerAdapter过期替代方案 最近在学习尚硅谷的<springboot核心技术篇>,项目中用到SpringMVC的自动配置和扩展 ...
- SpringBoot——Web开发(静态资源映射)
静态资源映射 SpringBoot对于SpringMVC的自动化配置都在WebMVCAutoConfiguration类中. 其中一个静态内部类WebMvcAutoConfigurationAdapt ...
- [SpringBoot——Web开发(使用Thymeleaf模板引擎)]
[文字只能描述片段信息,具体细节参考代码] https://github.com/HCJ-shadow/SpringBootPlus 引入POM依赖 <properties> <ja ...
- web开发-CORS支持
一.简介 Web 开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS 等等 1.1.CORS与JSONP相比 1.JSONP只能实现GET请求,而CORS支持所有类型的HTTP请求 ...
随机推荐
- L94
Early-morning births are genetically programmed THE notion that nothing good happens after midnight ...
- listen and translation exercise 53
It was hard work and there weren't any interesting things for him. You should be an expert with comp ...
- Dat.gui 使用教程
官方站点:http://workshop.chromeexperiments.com/examples/gui/ Dat.gui 使用教程:Dat.gui 是一个 GUI 组件,他可以为你的 demo ...
- linux 进程学习笔记-信号semaphore
信号灯(信号量)不是进程通信手段,其是用于控制和协调在进程间通信过程中的共享资源访问,就如同互斥锁(两者的区别可以参考这里) 可以将简单地将信号灯想象成一个计数器,初始时计数器值为n(有n个资源可供使 ...
- python程序打包工具 ── cx_Freeze
cx_Freeze是一个类似py2exe的工具,它们区别是py2exe是将python程序打包成windows下可以执行的exe文件的,而cx_Freeze则是将python程序打包为linux下可以 ...
- python之网络编程(概述及SOCKET)
概述(TCP/IP协议是一个协议族): TCP/IP 协议按照四层怎么划分:链路层,网络层,传输层,应用层(实际上是四层) TCP/IP 协议按照七层怎么划分:物理层,数据链路层,网络层,传输层,会话 ...
- Merge into使用详解( 同时执行inserts和updates操作 )
Merge是一个非常有用的功能,类似于MySQL里的insert into on duplicate key. Oracle在9i引入了merge命令, 通过这个merge你能够在一个SQL语句中对一 ...
- bzoj 3653 谈笑风生——主席树
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=3653 原来一直想怎么线段树合并.可是不会把角标挪一位. 查询的其实是子树内一段深度的点的 s ...
- YPBPR_PC下图像有毛刺或者水纹干扰的处理办法
VGA下一般是不做任何处理的,当然也不排除个别情况下,客户强烈要求,会打开的现象. (1)做一下auto color和auto adjust (2)调节一下ADC,如果是mstar的方案,将对比机的的 ...
- HDU1269(有向图缩点模板题)
迷宫城堡 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submis ...