SpringBoot扩展——应用Web Socket!
liuian 2025-07-17 20:40 66 浏览
应用Web Socket
目前,网络上的即时通信App有很多,如QQ、微信和飞书等,按照以往的技术来说,即时功能通常会采用服务器轮询和Comet技术来解决。
HTTP是非持久化、单向的网络协议,在建立连接后只允许浏览器向服务器发出请求后,服务器才能返回相应的数据。当需要即时通信时,在固定时间间隔(2s)通过轮询内由浏览器向服务器发送Request请求,再把最新的数据返回浏览器进行展示。这种方法最大的缺点就是要不断地向服务器发送请求,访问频率过高但是更新的数据量可能很小,这样就造成了资源浪费,增大了服务器的压力。
Web Socket技术的出现弥补了这一缺点,在Web Socket中,只需要服务器和浏览器通过HTTP完成一个“握手”的动作,然后单独建立一条TCP的通信通道即可进行数据的双向传送了,不需要再轮询服务器。
Web Socket简介
Web Socket是用在Web浏览器和服务器之间进行双向数据传输的一种协议,Web Socket协议出现在2008年,2011年成为国际标准,并且所有浏览器都支持。Web Socket基于TCP实现,包含初始的握手过程和后续的多次数据帧双向传输过程,其的目的是在Web Socket应用和Web Socket服务器进行多次双向通信时,避免服务器打开多个HTTP连接以节约资源,提高工作效率和资源利用率。
Web Socket技术的优点如下:
通过第一次HTTP Request建立了连接之后,后续的数据交换无须再重新发送HTTP Request,节省了带宽资源。
Web Socket的连接是双向通信的连接,在同一个TCP连接上既可以发送请求也可以接收请求。具有多路复用的功能(multiplexing),即几个不同的URI可以复用同一个Web Socket连接。这种访问方式与TCP连接非常相似,因为它借用了HTTP的一些概念,所以被称为Web Socket。
Web Socket协议不是一个全新的网络协议,而是利用了HTTP来建立连接。Web Socket创建连接的过程如下:
(1)Web Socket连接由浏览器发起,因为请求协议是一个标准的HTTP请求,请求的格式如下:
GET ws://localhost:3600/ws/chat HTTP/1.1
Host: localhost
Upgrade: websocket
Connection: Upgrade
Origin: http://localhost:3600
Sec-WebSocket-Key: client-random-string
Sec-WebSocket-Version: 13
注意,Web Socket请求和普通的HTTP请求有几点不同:
GET请求的地址不是类似/path/格式,而是以ws://开头的地址;
请求头Upgrade:websocket和Connection:Upgrade表示这个连接将要被转换为Web Socket连接;
Sec-WebSocket-Key用于标识该连接,并非用于加密数据;
Sec-WebSocket-Version指定了Web Socket的协议版本。
(2)服务器收到请求后会返回如下响应:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: server-random-string响应代码101表示本次连接的HTTP即将被更改,更改后的协议就是Upgrade:websocket指定的Web Socket协议。版本号和子协议规定了双方能理解的数据格式以及是否支持压缩等。
Web Socket的属性和方法
Web Socket的常见属性如表6.5所示。
Web Socket的常见方法有:
(1)WebSocket.close([code[, reason]]),关闭当前连接,使用示例如下:
ws.addEventListener("close", function(event) {
var code = event.code; var reason = event.reason;
var wasClean = event.wasClean;
// handle close event
});
(2)WebSocket.send(data),对要传输的数据进行排序,发送数据:
//发送文本
ws.send(“text message”);
//发送Blob
var file = document
.querySelector('input[type="file"]')
.files[0];
ws.send(file);
//发送图像数据或者ArrayBuffer
var img = canvas_context.getImageData(0, 0, 400, 320);
var binary = new Uint8Array(img.data.length);
for (var i = 0; i < img.data.length; i++) {
binary[i] = img.data[i];
}
//发送ArrayBuffer对象
ws.send(binary.buffer);
实战:Web Socket通信
新建一个Websocket-demo模块,进行Web Socket通信演练。
(1)添加Web Socket依赖到pom.xml中,代码如下:
<properties>
<java.version>11</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build> <plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
(2)在application.properties中添加Web访问的配置文件如下:
#排除静态文件夹
spring.devtools.restart.exclude=static/**,public/**
#关闭 Thymeleaf 的缓存
spring.thymeleaf.cache = false
#设置thymeleaf页面的编码
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
#设置thymeleaf页面的后缀
spring.thymeleaf.suffix=.html
#设置thymeleaf页面的存储路径
spring.thymeleaf.prefix=classpath:/templates/
#文件上传的配置
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
(3)新建一个Web Socket配置文件:
package com.example.websocketdemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import
org.springframework.web.socket.server.standard.ServerEndpointExporter;@Configuration
public class WebSocketConfig {
/**
* ServerEndpointExporter的作用
*
* 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
*
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
(4)新建一个Web Socket服务类,建立Web Socket连接、消息处理和返回:
package com.example.websocketdemo.server;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
@ServerEndpoint("/webSocket/{sid}")
@Component
public class WebSocketServer {
/**
* 静态变量,用来记录当前在线连接数。应当把它设计为线程安全的。
*/
private static AtomicInteger onlineNum = new AtomicInteger(); /**
* 存放每个客户端对应的Web SocketServer对象。
*/
private static ConcurrentHashMap<String,Session> sessionPools =
new ConcurrentHashMap<>();
/**
* 成功建立连接时调用
*/
@OnOpen
public void onOpen(Session session, @PathParam(value = "sid")
String userName) {
sessionPools.put(userName, session);
addOnlineCount();
System.out.println(userName + "连接上Web Socket,连接人数为:" +
onlineNum);
try {
sendMessage(session, "欢迎:" + userName + "加入连接!");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 关闭连接时调用
*/
@OnClose
public void onClose(@PathParam(value = "sid") String userName) {
sessionPools.remove(userName);
subOnlineCount();
System.out.println(userName + ",已经断开webSocket连接");
}
/**
* 收到客户端信息
*/
@OnMessage
public void onMessage(String message) throws IOException {
message = "客户端:" + message + ",已收到请求"; System.out.println(message);
for (Session session : sessionPools.values()) {
try {
sendMessage(session, message);
} catch (Exception e) {
e.printStackTrace();
continue;
}
}
}
/**
* 错误时调用
*/
@OnError
public void onError(Session session, Throwable throwable) {
throwable.printStackTrace();
}
private static void addOnlineCount() {
onlineNum.incrementAndGet();
}
private static void subOnlineCount() {
onlineNum.decrementAndGet();
}
/**
* 发送消息
*/
private void sendMessage(Session session, String message) throws
IOException {
if (session != null) {
synchronized (session) {
session.getBasicRemote().sendText(message);
}
}
}
/**
* 给指定用户发送信息 */
private void sendInfo(String userName, String message) {
Session session = sessionPools.get(userName);
try {
sendMessage(session, message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
(5)新建Web Socket的Web入口Controller:
package com.example.websocketdemo.controller;
import com.example.websocketdemo.server.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class SocketController {
@Autowired
private WebSocketServer webSocketServer;
@GetMapping("/webSocket")
public ModelAndView socket() {
ModelAndView modelAndView = new ModelAndView("/webSocket");
return modelAndView;
}
}
(6)新建一个Spring Boot启动类:
package com.example.websocketdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WebsocketDemoApplication {
public static void main(String[] args) {
SpringApplication.run(WebsocketDemoApplication.class, args);
}
}
启动项目,在浏览器中访问
http://127.0.0.1:8080/webSocket,打开控制台,可以看到显示结果如图6.25所示。
单击“开启socket”按钮,表明页面已经与服务器通过Web Socket建立了连接,打开浏览器的调试工具,如图6.26所示。
建立连接之后就可以在Web网页和服务器之间通信了。单击“发送消息”按钮,可以看到控制台上打印的消息日志,如图6.27所示。查看IDEA控制台可以看到,服务器已经收到消息并且把消息发送出去了,如图6.28所示。
至此即完成了Web Socket的通信。当浏览器和Web Socket服务端连接成功后,服务端会执行onOpen()方法;如果连接失败,发送、接收数据失败或者处理数据出现错误,则服务端会执行onError()方法;当浏览器接收到WebSocket服务端发送过来的数据时,会执行onMessage()方法。当前所有的操作都是采用异步回调的方式触发,可以获得更快的响应时间和更好的用户体验。
相关推荐
- 如何清理c盘缓存文件(怎么清除c盘的缓存)
-
具体步骤如下:1、首先在电脑桌面找到“计算机”图标(有的可能是我的电脑)双击左键打开。2、在打开的页面中找到“本地磁盘C”,然后右键单击。3、右键单击以后会出现一个菜单,我们在菜单的最底部扎到“属性”...
- 卡巴斯基全方位激活码(卡巴斯基全方位激活码在哪)
-
当你第一次用的时候能有个半年的免费激活吗码以后你修改系统内部的设置比如重装都会说你您输入的激活码已经超过允许安装的最大次数建议你先免费试用一个月或者用咱们国产的金山毕竟卡巴过分依赖病毒库...
- win10最清晰字体(window10怎么调字体清晰度)
-
首先,在Win10的桌面点击鼠标右键,选择“显示设置”在“显示设置”的界面下方,点击“高级显示设置”在“高级显示设置”的界面中,点击下方的“文本和其他项目大小的调整的高级选项”然后,点击“更改项目的大...
- 网络上xp是什么梗(xp是什么意思网络)
-
x是喜欢的意思,p是偏好的意思,原神xp党指的是一直在使用XP系统玩原神,不愿意更新系统的人。
- 电脑如何升级到win7
-
Windows7升级到Windows10系统需要使用官方的升级功能完成,以下是具体的操作方法:?1、在微软Windows10网站下载系统版本工具,完成右键以管理员身份打开【MediaCreationT...
- 手机下载pe启动盘(手机pe启动盘制作工具)
-
使用手机制作电脑PE启动盘需要以下步骤:1.手机需要支持OTG功能,并插入U盘。2.下载并安装一个名为“Rufus”的应用程序,它可以将U盘制作成可引导的PE启动盘。3.打开Rufus应用程序,...
- 2025年路由器推荐(2021年值得买的路由器)
-
水星AX18G这个无线速率是1800Mbps也属于“阉割”版的,跟标准的WiFi6还有一定差距。不过价格便宜,也可以作为WiFi6的尝试产品家里有宽带的话,买个无线路由器,约100元左右就行。每月交宽...
- 磁盘分区形式(磁盘分区形式MBR与GPT怎么转换)
-
怎么进行磁盘分区,可以参考以下步骤:步骤1.在“此电脑”上右键点击,选择“管理”,然后在“计算机管理”窗口的左侧列表中选择“磁盘管理”。在Windows10中也可以右键点击开始菜单,直接选择“磁盘...
- 固态硬盘使用寿命(固态硬盘使用寿命多久)
-
2012年9月买的联想U410超极本,到目前五年多,使用6300小时左右,电池损耗率只有15%+,固态硬盘升级120GB+原装的500GB机械硬盘,内存升级到16GB(上限了),加上Primocach...
- general(general是什么意思)
-
GENERAL的意思是:1、adj.一般的,普通的;综合的;大体的2、n.一般;将军,上将;常规短语:1、generaldesign总体设计2、generalhospital总医院;综合医...
- 手机处理器排名最新图(手机处理器排行榜全部)
-
众所周知,手机端SOC很少在插电模式下运行,因此能耗比在移动端CPU性能中特别重要。本文整理了主流的SOC能耗比情况,给大家购买手机做一个参考。SOC能耗比较高的,包括麒麟810,骁龙625,麒麟65...
- pdf版本怎么弄(怎么把word转为pdf)
-
回答如下:要将PDF文件恢复到以前的版本,您需要执行以下步骤:1.找到保存PDF文件的文件夹或位置。2.在该位置中找到以前的版本,这可能是备份文件、自动保存文件或之前保存的版本。3.如果您没有备...
- 一周热门
-
-
飞牛OS入门安装遇到问题,如何解决?
-
如何在 iPhone 和 Android 上恢复已删除的抖音消息
-
Boost高性能并发无锁队列指南:boost::lockfree::queue
-
大模型手册: 保姆级用CherryStudio知识库
-
用什么工具在Win中查看8G大的log文件?
-
如何在 Windows 10 或 11 上通过命令行安装 Node.js 和 NPM
-
威联通NAS安装阿里云盘WebDAV服务并添加到Infuse
-
Trae IDE 如何与 GitHub 无缝对接?
-
idea插件之maven search(工欲善其事,必先利其器)
-
如何修改图片拍摄日期?快速修改图片拍摄日期的6种方法
-
- 最近发表
- 标签列表
-
- python判断字典是否为空 (50)
- crontab每周一执行 (48)
- aes和des区别 (43)
- bash脚本和shell脚本的区别 (35)
- canvas库 (33)
- dataframe筛选满足条件的行 (35)
- gitlab日志 (33)
- lua xpcall (36)
- blob转json (33)
- python判断是否在列表中 (34)
- python html转pdf (36)
- 安装指定版本npm (37)
- idea搜索jar包内容 (33)
- css鼠标悬停出现隐藏的文字 (34)
- linux nacos启动命令 (33)
- gitlab 日志 (36)
- adb pull (37)
- python判断元素在不在列表里 (34)
- python 字典删除元素 (34)
- vscode切换git分支 (35)
- python bytes转16进制 (35)
- grep前后几行 (34)
- hashmap转list (35)
- c++ 字符串查找 (35)
- mysql刷新权限 (34)
