feat: 添加 WebSocket 基础设施

This commit is contained in:
2026-06-23 10:49:23 +08:00
parent d63ce3326b
commit d0ade3c469
3 changed files with 66 additions and 0 deletions

View File

@@ -27,6 +27,12 @@
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<!-- WebSocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!-- JPA 持久层 --> <!-- JPA 持久层 -->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>

View File

@@ -0,0 +1,28 @@
package com.webgame.webgamebackend.config;
import com.webgame.webgamebackend.ws.RoomWebSocketHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
/**
* WebSocket 配置
*
* 注册房间 WebSocket 端点,路径为 /ws/room。
* 客户端通过 ws://host/ws/room?roomId=xxx&token=xxx 连接。
*/
@Configuration
@EnableWebSocket
@RequiredArgsConstructor
public class WebSocketConfig implements WebSocketConfigurer {
private final RoomWebSocketHandler roomWebSocketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(roomWebSocketHandler, "/ws/room")
.setAllowedOrigins("*");
}
}

View File

@@ -0,0 +1,32 @@
package com.webgame.webgamebackend.ws;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
/**
* 房间 WebSocket 处理器
*
* 管理游戏房间内的实时通信,包括玩家加入、离开、游戏状态同步等。
* 后续任务将实现具体业务逻辑。
*/
@Component
public class RoomWebSocketHandler extends TextWebSocketHandler {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// 后续任务实现
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 后续任务实现
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
// 后续任务实现
}
}