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. eclipse 建立maven项目 显示红叉的解决方法

    1.建立好之后就会发现项目有红叉. 这时发现查查在main处,打开项目>属性>Java Build Path>source,发现里边有红叉(如下图),这是由于我们的src/main下 ...

  2. docker导入导出

    导出镜像 docker save -o centos7.tar centos # 导入本地镜像 docker load --input centos7.tar docker ps -a docker ...

  3. Hibernate集合映射

    可以在Hibernate中映射持久类的集合元素. 您需要从以下类型之一声明持久类中的集合类型: java.util.List java.util.Set java.util.SortedSet jav ...

  4. Struts2 主题和模板

    实际本章教程开始之前,让我们看看由http://struts.apache.org给出的几个定义: Term 描述 tag A small piece of code executed from wi ...

  5. MFC多国语言——配置文件

    前段时间,因工作需要,本地化了一个英文版本的产品. 在网上查阅了若干资料,在此进行一个简单的整理. 在MFC程序中,实现多国语言的方式很多,我们选择的是使用配置文件的方法. 在通过配置文件方式实现多国 ...

  6. 微信小程序 快键键

    快捷键 格式调整 - Ctrl+S:保存文件 - Ctrl+[, Ctrl+]:代码行缩进 - Ctrl+Shift+[, Ctrl+Shift+]:折叠打开代码块 - Ctrl+C Ctrl+V:复 ...

  7. mongo-connector来同步mongo

    个人博客:https://blog.sharedata.info/ 最近需要做mongo之间的同步,因此还是选择之前的工具mongo-connectorgitHub文档:https://github. ...

  8. PHP 可以获取客户端哪些访问信息

    php是一种弱类型的程序语言,但是最web的 在程序语言中有系统全局函数: $_SERVER <?php echo "".$_SERVER['PHP_SELF'];#当前正在 ...

  9. 位运算+引用+const+new/delete+内联函数、函数重载、函数缺省参数

    update 2014-05-17 一.位运算 应用: 1.判断某一位是否为1 2.只改变其中某一位,而保持其它位都不变 位运算操作: 1.& 按位与(双目): 将某变量中的某些位(与0位与) ...

  10. [转]JavaWeb之 Servlet执行过程 与 生命周期

    https://www.cnblogs.com/vmax-tam/p/4122105.html Servlet的概念 什么是Servlet呢? Java中有一个叫Servlet的接口,如果一个普通的类 ...