文章目录
- 前言
- 一、springboot集成WebSocket
- 二、后端代码实现
- 1.WebSocket服务端实现
- 2.业务逻辑实现
- 3.ObjectMapper的作用
- 三、前端代码实现
- 四、postman调试
- 总结
前言
在B/S开发的有些业务场景中后端需要向前端上报一些事件消息,比如某个用户登录或者退出时,后端需要将此事件通知其它已经登录的用户。此时,HTTP协议显然无法做到,那么我们就可以使用WebSocket协议,在springboot开发中如何集成WebSocket协议实现上述功能呢?
一、springboot集成WebSocket
pom.xml增加websocket依赖,如下:
<!--websocket依赖-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
二、后端代码实现
1.WebSocket服务端实现
增加websocket包,增加WebSocketConfig、WebServerEndpoint两个类,实现WebSocket服务端接口。
WebSocketConfig.java代码如下:
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;// 需要注入Bean的话必须声明为配置类
@Configuration
public class WebSocketConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter(){return new ServerEndpointExporter();}
}
WebServerEndpoint.java代码如下:
package com.example.demo.websocket;import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session