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请求 ...
随机推荐
- pod lib lint 报错 Unable to find a specification for `AMap2DMap` depended upon by `DingtalkPod
执行 pod验证 报错如下 ➜ DingtalkPod git:(2.0.0) ✗ pod lib lint --sources='https://github.com/AloneMonkey/Mo ...
- 设计四个线程,其中两个线程每次对j加1,另外两个线程每次对j减1
public class ManyThreads2 { private int j = 0; public synchronized void inc() { j++; System.out.prin ...
- 关闭windows10自动更新
用windows10的小伙伴们应该都被windows10自动更新这个问题折磨过.那到底要这样禁止windows10的自动更新呢? 百度上有一篇文章写的非常好,并且有配套,大家只要根据步骤操作即可,本人 ...
- dubbo的防痴呆设计
项目中也经常会遇到各种因为配置而引入的问题,很多技术支持解决不掉就找开发,结果发现大部分还是配置错误或网络不通等.如果在设计之初就能考虑到并针对这些问题做出应对设计,甚至给出异常的解决方案,确实可以减 ...
- ubuntu_deb安装命令
dpkg命令常用格式如下: sudo dpkg -I iptux.deb#查看iptux.deb软件包的详细信息,包括软件名称.版本以及大小等(其中-I等价于--info) sudo dpkg -c ...
- Redis的Spring配置讲解
Redis是一种特殊类型的数据库,他被称之为key-value存储 本文覆盖缓存和存储两方面进行说明,使用的是Spring 4.0和Java配置方式 代码地址下载地址:https://github.c ...
- shell expr 的使用注意事项
#!/bin/bash a=10 b=20 c=`expr $a + $b` echo "a + b :$c" c='expr $a + $b' echo "a + b ...
- HDOJ-2153
仙人球的残影 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Subm ...
- HDU - 5492 Find a path(方差公式+dp)
Find a path Frog fell into a maze. This maze is a rectangle containing NN rows and MM columns. Each ...
- [sdut] 1400 马的走法 dfs
Problem Description 在一个4*5的棋盘上,马的初始位置坐标(纵 横)位置由键盘输入,求马能返回初始位置的所有不同走法的总数(马走过的位置不能重复,马走“日”字).如果马的初始位置坐 ...