【广播式】

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. 解决Linux Kettle出现闪退问题

    linux环境, 运行sh spoon.sh打开图形化界面时经常出现闪退情况. 报错信息如下: cfgbuilder - Warning: The configuration parameter [o ...

  2. linux 进程学习笔记-等待子进程结束

    <!--[if !supportLists]-->Ÿ <!--[endif]-->等待子进程结束 pid_t waitpid(pid_t pid, int *stat_loc, ...

  3. perl 语言学习总结

    .#!/usr/bin/perl -w 内建警告信息,Perl发出警告 .字符串 . 连接符 .重复次数 .字符串与数字之间的自动转换 .; + += *= .= not and or xor .pr ...

  4. ACM学习历程—SNNUOJ 1110 传输网络((并查集 && 离线) || (线段树 && 时间戳))(2015陕西省大学生程序设计竞赛D题)

    Description Byteland国家的网络单向传输系统可以被看成是以首都 Bytetown为中心的有向树,一开始只有Bytetown建有基站,所有其他城市的信号都是从Bytetown传输过来的 ...

  5. javaCV入门指南:序章

    前言 从2016年6月开始写<javacv开发详解>系列,到而今的<javacv入门指南>,虽然仅隔了两年多时间,却也改变了很多东西. 比如我们的流媒体技术群从刚开始的两三个人 ...

  6. poj2955——括号匹配

    题目:http://poj.org/problem?id=2955 区间DP. 代码如下: #include<iostream> #include<cstdio> #inclu ...

  7. mysql 1069 数据库无法启动解决办法

    mysql无缘无故的启动不了了. 在控制台里面用root连接,报错10061. 在服务管理里面启动,报错1069. 在网上找了一些解决方法,删除my.ini之类的,都无效.后来在百度经验里面找到了可行 ...

  8. 3、scala数组

    一.Array .Array Buffer 1.Array 在Scala中,Array代表的含义与Java中类似,也是长度不可改变的数组. 此外,由于Scala与Java都是运行在JVM中,双方可以互 ...

  9. 微信小程序运行机制

    对于扫描接口B生成的带参小程序码的问题: (1)线上版本 扫描不同带参的小程序码会重新执行小程序的整个注册程序生命周期(详细生命周期函数见官方文档), (2)扫描相同的二维码的时候,目前微信官方给出的 ...

  10. SVN needs-lock 设置强制只读属性【转】

    https://www.jianshu.com/p/5942ab19620b 设置后向svn服务器添加文件时,会自动带上svn:needs-lock属性,默认是只读的要签出才能修改,以避免不必要的编辑 ...