SpringBoot实现WebSocket
创始人
2024-03-22 09:06:18
0

一、什么是websocket

WebSocket是HTML5下一种新的协议(websocket协议本质上是一个基于tcp的协议)
它实现了浏览器与服务器全双工通信,能更好的节省服务器资源和带宽并达到实时通讯的目的
Websocket是一个持久化的协议

二、新建SpringBoot工程

在这里插入图片描述
按照上图这样配置即可,点击下一步
因为本文章只实现websocket功能,所以只勾选SpringWeb,同时要保证springboot版本要低于3.0
在这里插入图片描述

创建完的工程目录如下
在这里插入图片描述

三、修改配置文件

将application.properties修改为application.yml,然后修改内容为

#服务器配置
server:port: 8081servlet:context-path: /api

在这里插入图片描述

修改POM.xml,在dependencies下加入所需依赖,加入后在空白处右键点击重新加载项目,下载对应依赖

org.springframeworkspring-websocket5.2.8.RELEASE

cn.hutoolhutool-all5.4.1

新建一个websocket包,包中新建两个类,代码如下

package com.example.demo.websocket;import cn.hutool.json.JSONUtil;
import org.springframework.stereotype.Component;import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;@ServerEndpoint(value = "/websocket/{userId}")
@Component
public class WebSocket {private static ConcurrentHashMap webSocketMap = new ConcurrentHashMap<>();//实例一个session,这个session是websocket的sessionprivate Session session;//新增一个方法用于主动向客户端发送消息public static void sendMessage(Object message, String userId) {WebSocket webSocket = webSocketMap.get(userId);if (webSocket != null) {try {webSocket.session.getBasicRemote().sendText(JSONUtil.toJsonStr(message));System.out.println("【websocket消息】发送消息成功,用户="+userId+",消息内容"+message.toString());} catch (IOException e) {e.printStackTrace();}}}public static ConcurrentHashMap getWebSocketMap() {return webSocketMap;}public static void setWebSocketMap(ConcurrentHashMap webSocketMap) {WebSocket.webSocketMap = webSocketMap;}//前端请求时一个websocket时@OnOpenpublic void onOpen(Session session, @PathParam("userId") String userId) {this.session = session;webSocketMap.put(userId, this);sendMessage("CONNECT_SUCCESS", userId);System.out.println("【websocket消息】有新的连接,连接id"+userId);}//前端关闭时一个websocket时@OnClosepublic void onClose() {webSocketMap.remove(this);System.out.println("【websocket消息】连接断开,总数:"+ webSocketMap.size());}//前端向后端发送消息@OnMessagepublic void onMessage(String message) {if (!message.equals("ping")) {System.out.println("【websocket消息】收到客户端发来的消息:"+message);}}
}
package com.example.demo.websocket;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;//开启WebSocket的支持,并把该类注入到spring容器中
@Configuration
public class WebSocketConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}}

四、项目完整结构如下

在这里插入图片描述

五、测试功能

点击运行按钮,可以看到控制台对应的输出,输出看到JVM running for 表示启动成功
在这里插入图片描述

在桌面新建一个websocket.html,将代码复制进去


本地websocket测试

双击打开这个html文件,页面的功能如下,websocket的通信地址要以ws://开头,因为我的springboot启动在8081端口,所以我的地址就是 ws://localhost:8081/api/websocket/{连接id},websocket前面加了api是前面在yml文件中配置了context-path,没有配置可以去掉。实际项目中,将连接id换成唯一的用户id即可向指定用户发送消息。
在这里插入图片描述

效果如下
在这里插入图片描述

这时候服务器控制台输出为
在这里插入图片描述

到此,SpringBoot搭建WebSocket就已经完成,还有什么问题可以私信作者~

上一篇:Redis单机集群

下一篇:硬件内存模型

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...
有效的括号 一、题目 给定一个只包括 '(',')','{','}'...
【Ctfer训练计划】——(三... 作者名:Demo不是emo  主页面链接:主页传送门 创作初心ÿ...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
带头循环双向链表来咯!!! 前言:继上文,我们了解了结构最简单的一种链表---单链表那么我们今天就来...