SpringBoot进阶教程(七十七)WebSocket
WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
v原理
很多网站为了实现推送技术,所用的技术都是轮询。轮询是在特定的时间间隔(如每1秒),由浏览器对服务器发出HTTP请求,然后由服务器返回最新的数据给客户端的浏览器。这种传统的模式带来很明显的缺点,即浏览器需要不断的向服务器发出请求,然而HTTP请求可能包含较长的头部,其中真正有效的数据可能只是很小的一部分,显然这样会浪费很多的带宽等资源。
而比较新的技术去做轮询的效果是Comet。这种技术虽然可以双向通信,但依然需要反复发出请求。而且在Comet中,普遍采用的长链接,也会消耗服务器资源。
在这种情况下,HTML5定义了WebSocket协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯。
v架构搭建
添加maven引用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
配置应用属性
server.port=8300
spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=true
spring.thymeleaf.prefix=classpath:/web/
spring.thymeleaf.encoding: UTF-8
spring.thymeleaf.suffix: .html
spring.thymeleaf.check-template-location: true
spring.thymeleaf.template-resolver-order: 1
添加WebSocketConfig
package com.test.config; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter; /**
* @Author chen bo
* @Date 2023/10
* @Des
*/
@Configuration
public class WebSocketConfig {
/**
* bean注册:会自动扫描带有@ServerEndpoint注解声明的Websocket Endpoint(端点),注册成为Websocket bean。
* 要注意,如果项目使用外置的servlet容器,而不是直接使用springboot内置容器的话,就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理。
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
添加WebSocket核心类
因为WebSocket是类似客户端服务端的形式(采用ws协议),那么这里的WebSocketServer其实就相当于一个ws协议的Controller
直接@ServerEndpoint("/imserver/{userId}") 、@Component启用即可,然后在里面实现@OnOpen开启连接,@onClose关闭连接,@onMessage接收消息等方法。
新建一个ConcurrentHashMap用于接收当前userId的WebSocket或者Session信息,方便IM之间对userId进行推送消息。单机版实现到这里就可以。集群版(多个ws节点)还需要借助 MySQL或者 Redis等进行订阅广播方式处理,改造对应的 sendMessage方法即可。
package com.test.util; import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component; import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.gson.JsonObject; /**
* WebSocket的操作类
* html页面与之关联的接口
* var reqUrl = "http://localhost:8300/websocket/" + cid;
* socket = new WebSocket(reqUrl.replace("http", "ws"));
*/
@Component
@Slf4j
@ServerEndpoint("/websocket/{sid}")
public class WebSocketServer { /**
* 静态变量,用来记录当前在线连接数,线程安全的类。
*/
private static AtomicInteger onlineSessionClientCount = new AtomicInteger(0); /**
* 存放所有在线的客户端
*/
private static Map<String, Session> onlineSessionClientMap = new ConcurrentHashMap<>(); /**
* 连接sid和连接会话
*/
private String sid;
private Session session; /**
* 连接建立成功调用的方法。由前端<code>new WebSocket</code>触发
*
* @param sid 每次页面建立连接时传入到服务端的id,比如用户id等。可以自定义。
* @param session 与某个客户端的连接会话,需要通过它来给客户端发送消息
*/
@OnOpen
public void onOpen(@PathParam("sid") String sid, Session session) {
/**
* session.getId():当前session会话会自动生成一个id,从0开始累加的。
*/
log.info("连接建立中 ==> session_id = {}, sid = {}", session.getId(), sid);
//加入 Map中。将页面的sid和session绑定或者session.getId()与session
//onlineSessionIdClientMap.put(session.getId(), session);
onlineSessionClientMap.put(sid, session); //在线数加1
onlineSessionClientCount.incrementAndGet();
this.sid = sid;
this.session = session;
sendToOne(sid, "上线了");
log.info("连接建立成功,当前在线数为:{} ==> 开始监听新连接:session_id = {}, sid = {},。", onlineSessionClientCount, session.getId(), sid);
} /**
* 连接关闭调用的方法。由前端<code>socket.close()</code>触发
*
* @param sid
* @param session
*/
@OnClose
public void onClose(@PathParam("sid") String sid, Session session) {
//onlineSessionIdClientMap.remove(session.getId());
// 从 Map中移除
onlineSessionClientMap.remove(sid); //在线数减1
onlineSessionClientCount.decrementAndGet();
log.info("连接关闭成功,当前在线数为:{} ==> 关闭该连接信息:session_id = {}, sid = {},。", onlineSessionClientCount, session.getId(), sid);
} /**
* 收到客户端消息后调用的方法。由前端<code>socket.send</code>触发
* * 当服务端执行toSession.getAsyncRemote().sendText(xxx)后,前端的socket.onmessage得到监听。
*
* @param message
* @param session
*/
@OnMessage
public void onMessage(String message, Session session) {
/**
* html界面传递来得数据格式,可以自定义.
* {"sid":"user","message":"hello websocket"}
*/
JsonObject jsonObject = JsonParser.parseString(message).getAsJsonObject();
String toSid = jsonObject.get("sid").getAsString();
String msg = jsonObject.get("message").getAsString();
log.info("服务端收到客户端消息 ==> fromSid = {}, toSid = {}, message = {}", sid, toSid, message); /**
* 模拟约定:如果未指定sid信息,则群发,否则就单独发送
*/
if (toSid == null || toSid == "" || "".equalsIgnoreCase(toSid)) {
sendToAll(msg);
} else {
sendToOne(toSid, msg);
}
} /**
* 发生错误调用的方法
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("WebSocket发生错误,错误信息为:" + error.getMessage());
error.printStackTrace();
} /**
* 群发消息
*
* @param message 消息
*/
private void sendToAll(String message) {
// 遍历在线map集合
onlineSessionClientMap.forEach((onlineSid, toSession) -> {
// 排除掉自己
if (!sid.equalsIgnoreCase(onlineSid)) {
log.info("服务端给客户端群发消息 ==> sid = {}, toSid = {}, message = {}", sid, onlineSid, message);
toSession.getAsyncRemote().sendText(message);
}
});
} /**
* 指定发送消息
*
* @param toSid
* @param message
*/
private void sendToOne(String toSid, String message) {
// 通过sid查询map中是否存在
Session toSession = onlineSessionClientMap.get(toSid);
if (toSession == null) {
log.error("服务端给客户端发送消息 ==> toSid = {} 不存在, message = {}", toSid, message);
return;
}
// 异步发送
log.info("服务端给客户端发送消息 ==> toSid = {}, message = {}", toSid, message);
toSession.getAsyncRemote().sendText(message);
/*
// 同步发送
try {
toSession.getBasicRemote().sendText(message);
} catch (IOException e) {
log.error("发送消息失败,WebSocket IO异常");
e.printStackTrace();
}*/
} }
添加controller
package com.test.controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; /**
* @Author chen bo
* @Date 2023/10
* @Des
*/
@Controller
public class HomeController {
/**
* 跳转到websocketDemo.html页面,携带自定义的cid信息。
* http://localhost:8300/demo/toWebSocketDemo/user
*
* @param cid
* @param model
* @return
*/
@GetMapping("/demo/toWebSocketDemo/{cid}")
public String toWebSocketDemo(@PathVariable String cid, Model model) {
model.addAttribute("cid", cid);
return "index";
} @GetMapping("hello")
@ResponseBody
public String hi(HttpServletResponse response) {
return "Hi";
}
}
添加html
注意:html文件添加在application.properties配置的对应目录中。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>聊天窗口</title>
</head>
<body>
<div>
我的用户名:
<input type="text" th:value="${cid}" readonly="readonly" id="cid"/>
</div>
<div id="chat-windows" style="width: 400px; height: 300px;overflow: scroll;border: blue 1px solid;"></div>
<div>收消息人用户名:<input id="toUserId" name="toUserId" type="text"></div>
<div>输入你要说的话:<input id="contentText" name="contentText" type="text"></div>
<div>
<button type="button" onclick="sendMessage()">发送消息</button>
</div>
</body> <script type="text/javascript">
var socket;
if (typeof (WebSocket) == "undefined") {
alert("您的浏览器不支持WebSocket");
} else {
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接 var cid = document.getElementById("cid").value;
console.log("cid-->" + cid);
var reqUrl = "http://localhost:8300/websocket/" + cid;
socket = new WebSocket(reqUrl.replace("http", "ws"));
//打开事件
socket.onopen = function () {
console.log("Socket 已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function (msg) {
console.log("onmessage--" + msg.data);
//发现消息进入 开始处理前端触发逻辑
var chatWindows = document.getElementById("chat-windows");
var pElement = document.createElement('p')
pElement.innerText = msg.data;
chatWindows.appendChild(pElement);
};
//关闭事件
socket.onclose = function () {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function () {
alert("Socket发生了错误");
//此时可以尝试刷新页面
}
//离开页面时,关闭socket
//jquery1.8中已经被废弃,3.0中已经移除
// $(window).unload(function(){
// socket.close();
//});
} function sendMessage() {
if (typeof (WebSocket) == "undefined") {
alert("您的浏览器不支持WebSocket");
} else {
var toUserId = document.getElementById('toUserId').value;
var contentText = document.getElementById('cid').value + ":" + document.getElementById('contentText').value;
var msg = '{"sid":"' + toUserId + '","message":"' + contentText + '"}';
console.log(msg);
var chatWindows = document.getElementById("chat-windows");
var chatWindows = document.getElementById("chat-windows");
var pElement = document.createElement('p');
pElement.innerText = "我:" + document.getElementById('contentText').value;
chatWindows.appendChild(pElement);
socket.send(msg);
}
} </script>
</html>
1对1模拟演练
启动项目后,在浏览器访问http://localhost:8300/demo/toWebSocketDemo/{cid} 跳转到对应页面,其中cid是用户名。
为了便于1对1测试,这里我们启动两个浏览器窗口。
http://localhost:8300/demo/toWebSocketDemo/阳光男孩
http://localhost:8300/demo/toWebSocketDemo/水晶女孩
按照要求输入对方用户信息之后,便可以输入你要说的话,畅快聊起来了。
效果图如下:

当然,如果收消息人用户名是自己的话,也可以自己给自己发送数据的。
群发模拟演练
为了便于群发测试,这里我们启动3个浏览器窗口。
http://localhost:8300/demo/toWebSocketDemo/阳光男孩
http://localhost:8300/demo/toWebSocketDemo/水晶女孩
http://localhost:8300/demo/toWebSocketDemo/路人A
由于sendToAll方法中定义群发的条件为:当不指定 toUserid时,则为群发。
效果图如下:

项目架构图如下:

v源码地址
https://github.com/toutouge/javademosecond
其他参考/学习资料:
作 者:请叫我头头哥
出 处:http://www.cnblogs.com/toutou/
关于作者:专注于基础平台的项目开发。如有问题或建议,请多多赐教!
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
特此声明:所有评论和私信都会在第一时间回复。也欢迎园子的大大们指正错误,共同进步。或者直接私信我
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是作者坚持原创和持续写作的最大动力!
#comment_body_3242240 { display: none }
SpringBoot进阶教程(七十七)WebSocket的更多相关文章
- SpringBoot进阶教程(七十四)整合ELK
在上一篇文章<SpringBoot进阶教程(七十三)整合elasticsearch >,已经详细介绍了关于elasticsearch的安装与使用,现在主要来看看关于ELK的定义.安装及使用 ...
- SpringBoot进阶教程(七十)SkyWalking
流行的APM(Application Performance Management工具有很多,比如Cat.Zipkin.Pinpoint.SkyWalking.优秀的监控工具还有很多,其它比如还有za ...
- SpringBoot进阶教程(七十一)详解Prometheus+Grafana
随着容器技术的迅速发展,Kubernetes已然成为大家追捧的容器集群管理系统.Prometheus作为生态圈Cloud Native Computing Foundation(简称:CNCF)中的重 ...
- SpringBoot进阶教程(二十七)整合Redis之分布式锁
在之前的一篇文章(<Java分布式锁,搞懂分布式锁实现看这篇文章就对了>),已经介绍过几种java分布式锁,今天来个Redis分布式锁的demo.redis 现在已经成为系统缓存的必备组件 ...
- SpringBoot进阶教程(七十三)整合elasticsearch
Elasticsearch 是一个分布式.高扩展.高实时的搜索与数据分析引擎.它能很方便的使大量数据具有搜索.分析和探索的能力.充分利用Elasticsearch的水平伸缩性,能使数据在生产环境变得更 ...
- SpringBoot进阶教程(六十七)RateLimiter限流
在上一篇文章nginx限流配置中,我们介绍了如何使用nginx限流,这篇文章介绍另外一种限流方式---RateLimiter. v限流背景 在早期的计算机领域,限流技术(time limiting)被 ...
- SpringBoot进阶教程(七十五)数据脱敏
无论对于什么业务来说,用户数据信息的安全性无疑都是非常重要的.尤其是在数字经济大火背景下,数据的安全性就显得更加重要.数据脱敏可以分为两个部分,一个是DB层面,防止DB数据泄露,暴露用户信息:一个是接 ...
- SpringBoot进阶教程(六十八)Sentinel实现限流降级
前面两篇文章nginx限流配置和SpringBoot进阶教程(六十七)RateLimiter限流,我们介绍了如何使用nginx和RateLimiter限流,这篇文章介绍另外一种限流方式---Senti ...
- SpringBoot进阶教程(二十九)整合Redis 发布订阅
SUBSCRIBE, UNSUBSCRIBE 和 PUBLISH 实现了 发布/订阅消息范例,发送者 (publishers) 不用编程就可以向特定的接受者发送消息 (subscribers). Ra ...
- SpringBoot进阶教程(五十九)整合Codis
上一篇博文<详解Codis安装与部署>中,详细介绍了codis的安装与部署,这篇文章主要介绍介绍springboot整合codis.如果之前看过<SpringBoot进阶教程(五十二 ...
随机推荐
- 6 种方式读取 Springboot 的配置,老鸟都这么玩(原理+实战)
大家好,我是小富- 从配置文件中获取属性应该是SpringBoot开发中最为常用的功能之一,但就是这么常用的功能,仍然有很多开发者在这个方面踩坑. 我整理了几种获取配置属性的方式,目的不仅是要让大家学 ...
- CKS 考试题整理 (07)-RBAC - RoleBinding
Context 绑定到 Pod 的 ServiceAccount 的 Role 授予过度宽松的权限,完成以下项目以减少权限集. Task 一个名为 web-pod 的现有 Pod 已在 namespa ...
- LLE算法在自然语言生成中的应用:实现文本到语音的情感迁移
目录 自然语言生成(Natural Language Generation,NLP)是人工智能领域的一个分支,它利用大量的文本数据训练出语言模型,从而实现对自然语言的生成和理解.在NLP中,情感迁移( ...
- 1.7 完善自定位ShellCode后门
在之前的文章中,我们实现了一个正向的匿名管道ShellCode后门,为了保证文章的简洁易懂并没有增加针对调用函数的动态定位功能,此类方法在更换系统后则由于地址变化导致我们的后门无法正常使用,接下来将实 ...
- 【Redis】基础命令
声明:本篇文章参考于该作者的# Redis从入门到精通:中级篇,大家有兴趣,去关注一下. 1.字符串(String) String(字符串)是Redis中最简单的一种数据结构,和MemCache数据结 ...
- WinUI(WASDK)使用MediaPipe检查人体姿态关键点
前言 之前有用这个MediaPipe.NET .NET包装库搞了手势识别,丰富了稚晖君的ElectronBot机器人的第三方上位机软件的功能,MediaPipe作为谷歌开源的机器视觉库,功能很丰富了, ...
- T-star高校挑战赛部分wp
web-1签到 checkin还是很基础的 网站上传存在js检测,禁用js即可上传 写PHP一句话木马上传,http://588f25a5.yunyansec.com/upload/test.php连 ...
- Linux shell:根据盘符定位硬盘在服务器上的位置
disk-light.sh #!/bin/bash t_dev=$1 [ -b "$t_dev" ] || { echo "-b failed: $t_dev" ...
- win10安装mysql-8.0.19-winx64
第一步:去官网下载安装 (重点)第二步:先解压,然后在mysql下创建一个my.ini文件,更改my.ini文件里面的两行安装目录,第二行加上\data,my.ini文件不能多或少一个符号,内容见文章 ...
- c#如何使用WASM跨语言调用?
介绍Wasm(WebAssembly) WebAssembly(简称Wasm)是一种用于基于堆栈的虚拟机的二进制指令格式.Wasm被设计为编程语言的可移植编译目标,支持在web上部署客户端和服务器应用 ...