项目中有需要使用到 WebSocket,这里记录一下:
添加依赖坐标,除了基本的 spring-boot-starter-web 依赖之外,还需要添加一个 websocket 相关的依赖:
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
添加 Configurer 配置类,将 websocket 访问路径入口与 handler绑定:
@Configuration
@EnableWebSocket
public class CmdWebSocketConfigurer implements WebSocketConfigurer {
@Autowired
ConsoleWebSocketHandler webSocketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
webSocketHandlerRegistry.addHandler(webSocketHandler, "/console");
}
}
创建上面配置的自定义的 ConsoleWebSocketHandler ,实现业务逻辑的编写:
@Component
public class ConsoleWebSocketHandler extends TextWebSocketHandler {
public void afterConnectionEstablished(WebSocketSession session);
protected void handleTextMessage(WebSocketSession session, TextMessage message);
protected void handlePongMessage(WebSocketSession session, PongMessage message);
public void handleTransportError(WebSocketSession session, Throwable exception);
public void afterConnectionClosed(WebSocketSession session, CloseStatus status);
}
我们可以将 WebSocketSession 保存下来,在之后通过这个对象给用户主动推送一些消息:
public interface WebSocketSession;
void sendMessage(WebSocketMessage<?> message);
void close() throws IOException;
在前端连接时,我们可以通过下面的代码建立连接:
websocket = new WebSocket("ws://" + window.location.host + "/console");
websocket.onopen = () => console.log("连接建立");
websocket.onclose = () => console.log("连接关闭");
websocket.onmessage = function(res) {
console.log("接收到消息");
}
参考资料
SpringBoot 实现 Websocket 通信详解 WebSocket-SockJS
|