springboot项目 使用websocket
时间: 2024-06-21 20:01:04 浏览: 335
spring-boot-starter-websocket-2.3.1.RELEASE.jar
5星 · 资源好评率100%
Spring Boot项目中使用WebSocket可以实现实时双向通信,比如聊天应用、在线通知等。WebSocket是一种在单个TCP连接上进行全双工通信的技术。以下是使用Spring Boot和WebSocket的基本步骤:
1. 添加依赖:在你的`pom.xml`或`build.gradle`文件中添加WebSocket相关依赖,例如Spring Websocket的`spring-boot-starter-websocket`。
```xml
<!-- Maven -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!-- Gradle (Kotlin) -->
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-websocket'
}
```
2. 配置WebSocket:在`application.properties`或`application.yml`中配置WebSocket服务器端点,如`server.webSocket.port`。
3. 创建WebSocket控制器:创建一个实现了`WebsocketHandler`接口的类,这是处理WebSocket连接和消息的地方。
```java
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.stereotype.Component;
@Component
public class ChatWebSocketHandler implements WebsocketHandler {
@Override
public void afterConnectionEstablished(WebSocketSession session) {
// 在连接建立后执行的操作
}
@MessageMapping("/chat")
public String handleMessage(String message) {
// 处理接收到的消息并返回响应
}
@SendTo("/topic/chat")
public String sendMessage(String message) {
// 发送消息到所有连接的客户端
return "Message sent to all!";
}
}
```
4. 注册WebSocket处理器:在`WebMvcConfigurer`中注册WebSocket处理器,使之被Spring扫描和启用。
```java
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
}
```
阅读全文