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. MII接口概念简述

    MII: Medium Independent Interface 媒体独立接口,也称介质无关接口 RMII: Reduced MII 简化媒体独立接口 GMII: Gigabit Medium In ...

  2. vmware workstation 9.0.2安装教程

    现在为您分享最新的VMware Workstation 9.0正式版(VMware Workstation 9.0.0 Build 812388)的下载,同时附上注册机或者注册激活码. 下载地址:   ...

  3. Mary的加盟

    Mary的加盟 1995年早些时候,我们招收了一个合同编制员——Mary Campione.她和我在后来的工作互助中相识.Mary的工作是帮助程序员使用平台特色如线程.我们很快意识到我们的工作如此相似 ...

  4. .net 连接Redis

    Redis安装 公司业务需要,弄了个类似于消息队列的东西,由客户端一直轮询取得信息.之前一直是走表的,但是效率以对表的使用都太过频繁,想试着用一下Redis,看看效率怎么样. 首先是安装Redis,这 ...

  5. 巧妙使用JQuery Clone 添加多行数据,并更新到数据库的实现代码

    web前端代码: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="BatchAd ...

  6. struts2之constant 讲解 (转)

    struts.serve.static.browserCache 该属性设置浏览器是否缓存静态内容.当应用处于开发阶段时,我们希望每次请求都获得服务器的最新响应,则可设置该属性为false. stru ...

  7. awk特征相同行的合并

    [root@linux-node1 ~]# cat test.txt hisk01 hisk02 hisk03 hisk04 hisk05 hisk06 hisk07 hisk08 [root@lin ...

  8. diango-tinymce富文本编译器

    应用到项目中 在settings.py中为INSTALLED_APPS添加编辑器应用 INSTALLED_APPS = ( ... 'tinymce', ) 在settings.py中添加编辑配置项 ...

  9. 看懂Gradle脚本(4)- Groovy语法之运算符重载

    继续讨论Task定义 回想一下前一篇文章的样例: task myTask { doLast { println 'hello world!' } } 这段脚本定义了一个名为myTask的任务.而且通过 ...

  10. 4、easyUI-七种布局(layout)

    1.为网页创建边框布局 边框布局(border layout)提供五个区域:east.west.north.south.center.以下是一些通常用法: north 区域可以用来显示网站的标语. s ...