Springboot整合WebSocket

1.application.properties

#设置服务端口号
server.port=8080 #thymeleaf配置
#是否启用模板缓存。
spring.thymeleaf.cache=false
#是否为Web框架启用Thymeleaf视图解析。
spring.thymeleaf.enabled=true
#在SpringEL表达式中启用SpringEL编译器。
spring.thymeleaf.enable-spring-el-compiler=true
#模板文件编码。
spring.thymeleaf.encoding=UTF-8
#要应用于模板的模板模式。另请参见Thymeleaf的TemplateMode枚举。
spring.thymeleaf.mode=HTML5
#在构建URL时添加前缀以查看名称的前缀。
spring.thymeleaf.prefix=classpath:/templates/
#Content-Type写入HTTP响应的值。
spring.thymeleaf.servlet.content-type=text/html
#在构建URL时附加到视图名称的后缀。
spring.thymeleaf.suffix=.html

2.pom.xml

<?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> <groupId>com.szw.learn</groupId>
<artifactId>websocket_01</artifactId>
<version>0.0.1-SNAPSHOT</version> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.16.RELEASE</version>
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<maven.test.skip>true</maven.test.skip>
<skipTests>true</skipTests>
<start-class>com.szw.learn.Websocket01Application</start-class>
</properties> <dependencies>
<!-- 使用web启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <!-- 测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <!-- 模板引擎 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> <!-- websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies> <repositories>
<repository>
<id>nexus-aliyun</id>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>nexus-aliyun</id>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories> <build>
<plugins>
<!-- 要将源码放上去,需要加入这个插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<configuration>
<attach>true</attach>
</configuration>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- 打包 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>

3.ServerEndpointExporter注册

package com.szw.learn.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration
public class WebsocketConfig {
/**
* <br>描 述: @Endpoint注解的websocket交给ServerEndpointExporter自动注册管理
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}

4.WebsocketEndpoint长连接端点

package com.szw.learn.websocket;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet; import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint; import org.springframework.stereotype.Component;
/**
*@ServerEndpoint(value="/websocket")value值必须以/开路
*备注:@ServerEndpoint注解类不支持使用@Autowire
*/
@Component
@ServerEndpoint(value="/websocket")
public class WebsocketEndpoint {
//存放该服务器该ws的所有连接。用处:比如向所有连接该ws的用户发送通知消息。
private static CopyOnWriteArraySet<WebsocketEndpoint> sessions = new CopyOnWriteArraySet<>(); private Session session; @OnOpen
public void onOpen(Session session){
System.out.println("java websocket:打开连接");
this.session = session;
sessions.add(this);
} @OnClose
public void onClose(Session session){
System.out.println("java websocket:关闭连接");
sessions.remove(this);
} @OnMessage
public void onMessage(Session session,String message) throws IOException{
System.out.println("java websocket 收到消息:"+message);
session.getBasicRemote().sendText("后台接收到您发的消息:"+message);
} @OnError
public void onError(Session session,Throwable error){
System.out.println("java websocket 出现错误");
} public Session getSession() {
return session;
} public void setSession(Session session) {
this.session = session;
}
}

5.index.html用户端

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8"></meta>
<title>websocket</title>
</head>
<body>
hello websocket<br/>
<input id="input_id" type="text" /><button onclick="sendMessage()">发送</button> <button onclick="closeWebsocket()">关闭</button>
<div id="message_id"></div>
</body>
<script type="text/javascript">
document.getElementById('input_id').focus();
var websocket = null;
//当前浏览前是否支持websocket
if("WebSocket" in window){
var url = "ws://127.0.0.1:8080/websocket";
websocket = new WebSocket(url);
}else{
alert("浏览器不支持websocket");
} websocket.onopen = function(event){
setMessage("打开连接");
} websocket.onclose = function(event){
setMessage("关闭连接");
} websocket.onmessage = function(event){
setMessage(event.data);
} websocket.onerror = function(event){
setMessage("连接异常");
} //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
closeWebsocket();
} //关闭websocket
function closeWebsocket(){
//3代表已经关闭
if(3!=websocket.readyState){
websocket.close();
}else{
alert("websocket之前已经关闭");
}
} //将消息显示在网页上
function setMessage(message){
document.getElementById('message_id').innerHTML += message + '<br/>';
} //发送消息
function sendMessage(){
//1代表正在连接
if(1==websocket.readyState){
var message = document.getElementById('input_id').value;
setMessage(message);
websocket.send(message);
}else{
alert("websocket未连接");
}
document.getElementById('input_id').value="";
document.getElementById('input_id').focus();
}
</script>
</html>

6.WebsocketController测试地址

package com.szw.learn.websocket;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; @RequestMapping("websocket")
@Controller
public class WebsocketController { private static final String INDEX = "websocket/index"; @RequestMapping("index")
public ModelAndView index(){
return new ModelAndView(INDEX);
}
}

7.Websocket01Application启动类

package com.szw.learn;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class Websocket01Application {
public static void main(String[] args) {
System.setProperty("spring.devtools.restart.enabled", "false");
SpringApplication.run(Websocket01Application.class, args);
}
}

8.测试

Springboot WebSocket例子的更多相关文章

  1. Springboot+Websocket+JWT实现的即时通讯模块

    场景 目前做了一个接口:邀请用户成为某课程的管理员,于是我感觉有能在用户被邀请之后能有个立马通知他本人的机(类似微博.朋友圈被点赞后就有立马能收到通知一样),于是就闲来没事搞了一套. ​ 涉及技术栈 ...

  2. springboot - websocket实现及原理

    本文章包括websocket面试相关问题以及spring boot如何整合webSocket. 参考文档 https://blog.csdn.net/prayallforyou/article/det ...

  3. SpringBoot+WebSocket

    SpringBoot+WebSocket 只需三个步骤 导入依赖 <dependency> <groupId>org.springframework.boot</grou ...

  4. springboot+websocket+sockjs进行消息推送【基于STOMP协议】

    springboot+websocket+sockjs进行消息推送[基于STOMP协议] WebSocket是在HTML5基础上单个TCP连接上进行全双工通讯的协议,只要浏览器和服务器进行一次握手,就 ...

  5. SpringBoot WebSocket STOMP 广播配置

    目录 1. 前言 2. STOMP协议 3. SpringBoot WebSocket集成 3.1 导入websocket包 3.2 配置WebSocket 3.3 对外暴露接口 4. 前端对接测试 ...

  6. Java Springboot webSocket简单实现,调接口推送消息到客户端socket

    Java Springboot webSocket简单实现,调接口推送消息到客户端socket 后台一般作为webSocket服务器,前台作为client.真实场景可能是后台程序在运行时(满足一定条件 ...

  7. spring boot 初试,springboot入门,springboot helloworld例子

    因为项目中使用了spring boot ,之前没接触过,所以写个helloworld玩玩看,当做springboot的一个入门例子.搜索 spring boot.得到官方地址:http://proje ...

  8. Springboot+websocket+定时器实现消息推送

    由于最近有个需求,产品即将到期(不同时间段到期)时给后台用户按角色推送,功能完成之后在此做个小结 1. 在启动类中添加注解@EnableScheduling package com.hsfw.back ...

  9. springboot+websocket 归纳收集

    websocket是h5后的技术,主要实现是一个长连接跟tomcat的comet技术差不多,但websocket是基于web协议的,有更广泛的支持.当然,在处理高并发的情况下,可以结合tomcat的a ...

随机推荐

  1. JavaScript 测试和捕捉

    try 语句允许我们定义在执行时进行错误测试的代码块. catch 语句允许我们定义当 try 代码块发生错误时,所执行的代码块. JavaScript 语句 try 和 catch 是成对出现的.

  2. 分享一个编译期输出TODO,FIXME列表的宏

    效果,双击能跳到相应位置: >------ Build started: Project: TestVS2013, Configuration: Debug Win32 ------ > ...

  3. 错误命令“if not exist "\Dll" mkdir "\Dll" xcopy "\bin\Debug\*.*" "F:\647\VS项目\EtrolMes2014SY\Framework\Dll" /e /i /y”已退出,代码为 9009

    分析错误 第一步:观察错误,发现plugin文件夹中未生成对应的编译文件. 第二步:XCOPY命令无法执行,百度xcopy为何无法执行 第三步,搜索,发现环境变量未配置正确. 就是环境变量path(大 ...

  4. JS中的加号+运算符详解

    加号+运算符 在 JavaScript 中,加法的规则其实很简单,只有两种情况: 把数字和数字相加 把字符串和字符串相加 所有其他类型的值都会被自动转换成这两种类型的值. 为了能够弄明白这种隐式转换是 ...

  5. 【BZOJ4448】[Scoi2015]情报传递 主席树+LCA

    [BZOJ4448][Scoi2015]情报传递 Description 奈特公司是一个巨大的情报公司,它有着庞大的情报网络.情报网络中共有n名情报员.每名情报员能有若干名(可能没有)下线,除1名大头 ...

  6. 类与类之间关系,用C#和JavaScript体现

    前言 在面向对象中,类之间的关系有六种,分别是: 关联关系(Association) 泛化关系(Generalization) 依赖(Dependency) 聚合(Aggregation) 组合(Co ...

  7. 数据库几种连接方式的(左右union all)

    A表 id  name 1 bai 2 zhang 3 li B表 a_id score 1 80 2 70 1 30 左连接: select A.* ,B.* from A a left outer ...

  8. KVC && KVO 初见

    Look,这是一个很简单的要求,点击Add me,age +1. 想一想的话很简单的,设置一个属性Nsinteger age,点击button add me,直接加1在重新显示Lable就好啦,不过, ...

  9. 双向认证 HTTPS双向认证

    [微信支付]微信小程序支付开发者文档 https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=4_3 HTTPS双向认证使用说明 ...

  10. velocity 遍历EventHandler Iterator

    EventHandlerUtil 类的 iterateOverEventHandlers方法 for (Iterator i = handlerIterator; i.hasNext();){ Eve ...