WebSocket是HTML5下一种新的协议(websocket协议本质上是一个基于tcp的协议)
它实现了浏览器与服务器全双工通信,能更好的节省服务器资源和带宽并达到实时通讯的目的
Websocket是一个持久化的协议
按照上图这样配置即可,点击下一步
因为本文章只实现websocket功能,所以只勾选SpringWeb,同时要保证springboot版本要低于3.0
创建完的工程目录如下
将application.properties修改为application.yml,然后修改内容为
#服务器配置
server:port: 8081servlet:context-path: /api
修改POM.xml,在dependencies下加入所需依赖,加入后在空白处右键点击重新加载项目,下载对应依赖
org.springframework spring-websocket 5.2.8.RELEASE
cn.hutool hutool-all 5.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就已经完成,还有什么问题可以私信作者~