springboot整合websocket并配置自定义端口
时间: 2023-12-19 20:07:12 浏览: 1136
1. 首先在pom.xml中添加依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
2. 在Spring Boot启动类上添加@EnableWebSocket注解开启WebSocket支持。
```java
@SpringBootApplication
@EnableWebSocket
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
3. 创建WebSocket处理器,继承自TextWebSocketHandler,并实现handleTextMessage方法。在该方法中处理收到的消息,并发送响应消息。
```java
@Component
public class WebSocketHandler extends TextWebSocketHandler {
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String payload = message.getPayload();
System.out.println("收到消息:" + payload);
session.sendMessage(new TextMessage("服务器响应:" + payload));
}
}
```
4. 配置WebSocket端口,打开application.properties文件并添加如下配置:
```properties
server.port=8080
server.servlet.context-path=/
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
# WebSocket配置
server.endpoint.prefix=/ws
spring.websocket.path=/ws
```
其中server.port为Spring Boot应用端口,server.endpoint.prefix为WebSocket的端点前缀,spring.websocket.path为WebSocket的路径。
5. 在配置类中创建WebSocketHandler对象,并将其注册到WebSocket处理器中。
```java
@Configuration
public class WebSocketConfig implements WebSocketConfigurer {
@Autowired
private WebSocketHandler webSocketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(webSocketHandler, "/ws").setAllowedOrigins("*");
}
}
```
6. 启动Spring Boot应用,访问http://localhost:8080/ws即可连接WebSocket。
阅读全文