SpringBoot可以通過集成Spring框架中的WebSocket模塊來實現(xiàn)WebSocket通信。以下是一個簡單的示例:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
@Component
public class MyWebSocketHandler extends TextWebSocketHandler {
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 處理接收到的消息
session.sendMessage(new TextMessage("Hello, " + message.getPayload()));
}
}
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Autowired
private MyWebSocketHandler myWebSocketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myWebSocketHandler, "/websocket");
}
}
以上就是SpringBoot實現(xiàn)WebSocket通信的簡單示例。您可以根據(jù)實際需求來進一步擴展和定制WebSocket功能。