【广播式】

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的更多相关文章

  1. SpringBoot Web开发(5) 开发页面国际化+登录拦截

    SpringBoot Web开发(5) 开发页面国际化+登录拦截 一.页面国际化 页面国际化目的:根据浏览器语言设置的信息对页面信息进行切换,或者用户点击链接自行对页面语言信息进行切换. **效果演示 ...

  2. SpringBoot Web开发(4) Thymeleaf模板与freemaker

    SpringBoot Web开发(4) Thymeleaf模板与freemaker 一.模板引擎 常用得模板引擎有JSP.Velocity.Freemarker.Thymeleaf SpringBoo ...

  3. 【SpringBoot】SpringBoot Web开发(八)

    本周介绍SpringBoot项目Web开发的项目内容,及常用的CRUD操作,阅读本章前请阅读[SpringBoot]SpringBoot与Thymeleaf模版(六)的相关内容 Web开发 项目搭建 ...

  4. springboot web开发【转】【补】

    pom.xml引入webjars的官网 https://www.webjars.org/ https://www.thymeleaf.org/doc/tutorials/3.0/usingthymel ...

  5. SpringBoot(四): SpringBoot web开发 SpringBoot使用jsp

    1.在SpringBoot中使用jsp,需要在pom.xml文件中添加依赖 <!--引入Spring Boot内嵌的Tomcat对JSP的解析包--> <dependency> ...

  6. Spring-boot -Web开发

    1).创建SpringBoot应用,选中我们需要的模块: 2).SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来 3).自己编写业务代码: 文件名的功能 x ...

  7. SpringBoot Web开发(3) WebMvcConfigurerAdapter过期替代方案

    springboot2.0中 WebMvcConfigurerAdapter过期替代方案 最近在学习尚硅谷的<springboot核心技术篇>,项目中用到SpringMVC的自动配置和扩展 ...

  8. SpringBoot——Web开发(静态资源映射)

    静态资源映射 SpringBoot对于SpringMVC的自动化配置都在WebMVCAutoConfiguration类中. 其中一个静态内部类WebMvcAutoConfigurationAdapt ...

  9. [SpringBoot——Web开发(使用Thymeleaf模板引擎)]

    [文字只能描述片段信息,具体细节参考代码] https://github.com/HCJ-shadow/SpringBootPlus 引入POM依赖 <properties> <ja ...

  10. web开发-CORS支持

    一.简介 Web 开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS 等等 1.1.CORS与JSONP相比 1.JSONP只能实现GET请求,而CORS支持所有类型的HTTP请求 ...

随机推荐

  1. hdu-5780 gcd(数学)

    题目链接: gcd Time Limit: 2000/1000 MS (Java/Others)     Memory Limit: 131072/131072 K (Java/Others) Pro ...

  2. STL中mem_fun和mem_fun_ref的用法

    例如:假设有如下的代码: class Employee { public: int DoSomething(){} } std::vector<Employee> Emps; 假设我们要调 ...

  3. ORA-21561: OID generation failed

    ORA-21561: OID generation failed 从AIX机器上连Linux上的Oracle数据库时报ORA-21561: OID generation failed错误.不是因为AI ...

  4. 关于STM32中GPIO的8种工作模式

    CSDN:http://blog.csdn.net/l20130316 博客园:http://www.cnblogs.com/luckyalan/ 1 综述 I/O口是单片机中非常常用的外设,STM3 ...

  5. MySQL 单笔订单满6个及以上产品且金额>=300赠送优惠券_20161103

    活动内容: 单笔订单满6个及以上产品(帽子.浴巾除外),金额满赠300元,即赠送300-10元(除帽子.浴巾外)优惠券一张.需求数据:满足条件的用户ID活动时间:11.2-11.5(4天)活动规则:① ...

  6. UOJ_407_【IOI2018】狼人

    http://uoj.ac/problem/407 分析: 分别建立最小/最大kruskal重构树. 每次询问给出的两个点能走到的部分分别对应两棵树\(dfs\)序的一段区间. 转化成判断矩形中是否有 ...

  7. ubuntu下 修改主机名

    sudo gedit /etc/hostname 写入: sudo gedit /etc/hosts

  8. jquery 插件 国外

    http://www.jqueryrain.com/demo/jquery-portfolio-gallery-plugin/

  9. [hiho1584]Bounce

    题意:找出图中经过一次的格子个数. 解题关键: 组合数学的思想:先找出总的经过格子的次数,然后减去2倍的经过2次的格子个数. 1.总的求法:将长延展,当延展到n倍时,能够恰好到达右边的两个端点,则总格 ...

  10. Python学习——使用dict和set

    dict Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度. 举个例子,假设要根据同学的名字 ...