springboot 配置WebSocket支持socketio长链接 前后端代码
时间: 2024-09-19 18:08:09 浏览: 72
Spring Boot配置WebSocket支持Socket.io长连接的过程包括以下几个步骤:
1. 添加依赖:首先,你需要在`pom.xml`文件中添加WebSocket和Socket.io相关的依赖。例如,如果你使用的是WebFlux,可以添加如下依赖:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>socket.io-client</artifactId>
<version>4.5.0</version>
</dependency>
</dependencies>
```
2. 配置WebSocket:在Spring Boot应用启动类上添加`@EnableWebSocketMessageBroker`注解,并创建一个WebSocket的消息发布者(`@MessageMapping`)和订阅者(`@SubscribeMapping`):
```java
@SpringBootApplication
@EnableWebSocketMessageBroker
public class Application {
@Bean
public WebSocketMessageBrokerConfigurer configurer() {
return new WebSocketMessageBrokerConfigurerAdapter() {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
};
}
// ...其他业务代码...
}
```
3. 前端(HTML和JavaScript)部分:使用Socket.IO库连接到WebSocket服务器。这里是一个简单的示例:
```html
<script src="https://cdn.socket.io/socket.io-4.5.0.js"></script>
<script>
var socket = io('ws://localhost:8080/ws', {transports: ['websocket']});
socket.connect(); // 初始化连接
// 发送消息
function sendMessage(message) {
socket.emit('message', message);
}
// 接收消息
socket.on('message', function(data) {
console.log('Received:', data);
});
</script>
```
阅读全文