【广播式】

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. 一个关于前端页面的小标签<tbody>

    我们有时候希望将表格的内容分为多个模块,这时候就可以使用<tbody>标签,它是<table>的字标签,是<tr>的父标签,可以使用它达到一种设置样式的结果.

  2. intent实现Activity之间跳转的各种传值

    一.在Activity之间传递String类型的数据 传递 @Override public void onClick(View v) { String num1 = firstNum.getText ...

  3. ACM学习历程——HDU5017 Ellipsoid(模拟退火)(2014西安网赛K题)

    ---恢复内容开始--- Description Given a 3-dimension ellipsoid(椭球面) your task is to find the minimal distanc ...

  4. UDK更改启动画面及载入动画

    转自:http://www.unrealchina.org/forum.php?mod=viewthread&tid=246&extra=page%3D1 方法很简单: 1.更改启动画 ...

  5. ubuntu 修改资源镜像

    要修改的文件 /etc/apt/sources.list 原资源镜像文件 deb http://mirrors.aliyun.com/ubuntu/ yakkety main multiverse r ...

  6. android apk 防止反编译技术第二篇-运行时修改字节码

    上一篇我们讲了apk防止反编译技术中的加壳技术,如果有不明白的可以查看我的上一篇博客http://my.oschina.net/u/2323218/blog/393372.接下来我们将介绍另一种防止a ...

  7. WebService基础入门(转)

    一.概念: 1.WebService,顾名思义就是基于Web的服务.它使用Web(HTTP)方式,接收和响应外部系统的某种请求.从而实现远程调用. 2.我们可以调用互联网上查询天气信息Web服务,然后 ...

  8. [51nod1102]面积最大的矩形(单调栈||预处理)

    题意:求序列上某区间最小值乘区间长度的最大值. 解题关键:很早就在<挑战程序设计竞赛>中见过了,单调栈模板题,注意弹栈时如何处理后面的元素. 法一:单调栈 #include<bits ...

  9. SO_REUSEADDR的分析

    今天协议个socket程序时碰到了这个问题,选自博客http://www.cppblog.com/ace/archive/2006/04/29/6446.html 敲完代码,等下看它.

  10. SelectObject()函数详解

    SelectObject 把一个对象(位图.画笔.画刷等)选入指定的设备描述表.新的对象代替同一类型的老对象. HGDIOBJ SelectObject(   HDC hdc,          // ...