SpringBoot可以通过集成Spring框架中的WebSocket模块来实现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实现WebSocket通信的简单示例。您可以根据实际需求来进一步扩展和定制WebSocket功能。