在Spring Boot中使用WebSocket可以通过以下步骤实现:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new WebSocketHandler(), "/ws").setAllowedOrigins("*");
}
}
@Component
public class WebSocketHandler extends TextWebSocketHandler {
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 处理收到的消息
String payload = message.getPayload();
session.sendMessage(new TextMessage("收到消息:" + payload));
}
}
var socket = new WebSocket("ws://localhost:8080/ws");
socket.onopen = function() {
console.log("连接成功");
};
socket.onmessage = function(event) {
console.log("收到消息:" + event.data);
};
socket.send("Hello, WebSocket!");
以上就是在Spring Boot中使用WebSocket的基本步骤,通过WebSocket可以实现实时通信和消息推送功能。