2026-06-23 10:49:23 +08:00
|
|
|
|
package com.webgame.webgamebackend.ws;
|
|
|
|
|
|
|
2026-06-23 10:55:06 +08:00
|
|
|
|
import cn.dev33.satoken.stp.StpUtil;
|
|
|
|
|
|
import com.alibaba.fastjson2.JSON;
|
|
|
|
|
|
import com.alibaba.fastjson2.JSONObject;
|
|
|
|
|
|
import com.webgame.webgamebackend.service.GomokuGameService;
|
|
|
|
|
|
import com.webgame.webgamebackend.ws.dto.WsInboundMessage;
|
|
|
|
|
|
import com.webgame.webgamebackend.ws.dto.WsMessage;
|
2026-06-23 10:59:49 +08:00
|
|
|
|
import com.webgame.webgamebackend.ws.dto.WsOutboundMessage;
|
2026-06-24 09:50:01 +08:00
|
|
|
|
import jakarta.annotation.PostConstruct;
|
2026-06-23 10:55:06 +08:00
|
|
|
|
import lombok.RequiredArgsConstructor;
|
|
|
|
|
|
import lombok.extern.slf4j.Slf4j;
|
2026-06-23 10:49:23 +08:00
|
|
|
|
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;
|
|
|
|
|
|
|
2026-06-23 10:55:06 +08:00
|
|
|
|
import java.io.IOException;
|
|
|
|
|
|
import java.net.URI;
|
|
|
|
|
|
import java.util.Map;
|
|
|
|
|
|
|
2026-06-23 10:49:23 +08:00
|
|
|
|
/**
|
|
|
|
|
|
* 房间 WebSocket 处理器
|
|
|
|
|
|
*
|
2026-06-24 09:50:01 +08:00
|
|
|
|
* 处理客户端连接、断开与消息路由。消息类型通过 WsMessageRouter 注册表分发,
|
|
|
|
|
|
* 新增消息类型只需注册对应的 WsMessageHandler,无需修改路由逻辑。
|
2026-06-23 10:55:06 +08:00
|
|
|
|
* 通过 URL 参数传递 roomId 和 token 完成认证与房间绑定。
|
2026-06-23 10:49:23 +08:00
|
|
|
|
*/
|
2026-06-23 10:55:06 +08:00
|
|
|
|
@Slf4j
|
2026-06-23 10:49:23 +08:00
|
|
|
|
@Component
|
2026-06-23 10:55:06 +08:00
|
|
|
|
@RequiredArgsConstructor
|
2026-06-23 10:49:23 +08:00
|
|
|
|
public class RoomWebSocketHandler extends TextWebSocketHandler {
|
|
|
|
|
|
|
2026-06-23 10:55:06 +08:00
|
|
|
|
private final RoomSessionManager sessionManager;
|
|
|
|
|
|
private final GomokuGameService gomokuGameService;
|
2026-06-24 09:50:01 +08:00
|
|
|
|
private final WsMessageRouter router;
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 注册所有消息类型与对应处理器
|
|
|
|
|
|
*
|
|
|
|
|
|
* 新增消息类型只需在此方法中添加一行 router.register(...) 即可。
|
|
|
|
|
|
*/
|
|
|
|
|
|
@PostConstruct
|
|
|
|
|
|
public void registerHandlers() {
|
|
|
|
|
|
// 落子:需从 data 中提取 row, col
|
|
|
|
|
|
router.register(WsInboundMessage.PLACE_STONE, (roomId, userId, data, sm) -> {
|
|
|
|
|
|
int row = data.getIntValue("row");
|
|
|
|
|
|
int col = data.getIntValue("col");
|
|
|
|
|
|
gomokuGameService.placeStone(roomId, userId, row, col, sm);
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
// 聊天
|
|
|
|
|
|
router.register(WsInboundMessage.CHAT, (roomId, userId, data, sm) -> {
|
|
|
|
|
|
String content = data.getString("content");
|
|
|
|
|
|
handleChat(roomId, userId, content);
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
// 准备/取消准备
|
|
|
|
|
|
router.register(WsInboundMessage.READY,
|
|
|
|
|
|
(roomId, userId, data, sm) -> gomokuGameService.toggleReady(roomId, userId, sm));
|
|
|
|
|
|
|
|
|
|
|
|
// 认输
|
|
|
|
|
|
router.register(WsInboundMessage.RESIGN,
|
|
|
|
|
|
(roomId, userId, data, sm) -> gomokuGameService.resign(roomId, userId, sm));
|
|
|
|
|
|
|
|
|
|
|
|
// 求和请求
|
|
|
|
|
|
router.register(WsInboundMessage.DRAW_REQUEST,
|
|
|
|
|
|
(roomId, userId, data, sm) -> gomokuGameService.requestDraw(roomId, userId, sm));
|
|
|
|
|
|
|
|
|
|
|
|
// 回应求和:需从 data 中提取 accept
|
|
|
|
|
|
router.register(WsInboundMessage.DRAW_RESPONSE, (roomId, userId, data, sm) -> {
|
|
|
|
|
|
boolean accept = data.getBooleanValue("accept");
|
|
|
|
|
|
gomokuGameService.respondToDraw(roomId, userId, accept, sm);
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
// 离开房间
|
|
|
|
|
|
router.register(WsInboundMessage.LEAVE,
|
|
|
|
|
|
(roomId, userId, data, sm) -> gomokuGameService.leaveRoom(roomId, userId, sm));
|
|
|
|
|
|
|
|
|
|
|
|
// 开始游戏(仅房主)
|
|
|
|
|
|
router.register(WsInboundMessage.START,
|
|
|
|
|
|
(roomId, userId, data, sm) -> gomokuGameService.startGame(roomId, userId, sm));
|
|
|
|
|
|
|
|
|
|
|
|
log.info("[WS] 已注册 {} 个消息处理器", router.size());
|
|
|
|
|
|
}
|
2026-06-23 10:55:06 +08:00
|
|
|
|
|
2026-06-23 10:49:23 +08:00
|
|
|
|
@Override
|
|
|
|
|
|
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
|
2026-06-23 10:55:06 +08:00
|
|
|
|
// 从 URL 参数中提取 roomId 和 token
|
|
|
|
|
|
URI uri = session.getUri();
|
|
|
|
|
|
if (uri == null) {
|
|
|
|
|
|
session.close(CloseStatus.BAD_DATA);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
String query = uri.getQuery();
|
|
|
|
|
|
if (query == null) {
|
|
|
|
|
|
session.close(CloseStatus.BAD_DATA);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
String roomId = getQueryParam(query, "roomId");
|
|
|
|
|
|
String token = getQueryParam(query, "token");
|
|
|
|
|
|
|
|
|
|
|
|
if (roomId == null || token == null) {
|
|
|
|
|
|
session.close(CloseStatus.BAD_DATA);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 通过 token 获取用户 ID
|
|
|
|
|
|
Object loginId = StpUtil.getLoginIdByToken(token);
|
|
|
|
|
|
if (loginId == null) {
|
|
|
|
|
|
session.close(CloseStatus.POLICY_VIOLATION);
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
String userId = loginId.toString();
|
|
|
|
|
|
|
2026-06-23 13:49:15 +08:00
|
|
|
|
// 注册会话(内部会清理同用户的旧会话)
|
2026-06-23 10:55:06 +08:00
|
|
|
|
sessionManager.addSession(roomId, userId, session);
|
2026-06-23 13:49:15 +08:00
|
|
|
|
|
|
|
|
|
|
// 取消断线超时定时器(重连场景)
|
|
|
|
|
|
gomokuGameService.cancelDisconnectTimeout(roomId, userId);
|
|
|
|
|
|
|
2026-06-23 10:55:06 +08:00
|
|
|
|
log.info("[WS] 连接建立, roomId={}, userId={}, sessionId={}", roomId, userId, session.getId());
|
2026-06-23 10:49:23 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
@Override
|
|
|
|
|
|
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
|
2026-06-23 10:55:06 +08:00
|
|
|
|
String payload = message.getPayload();
|
|
|
|
|
|
String userId = sessionManager.getUserId(session);
|
|
|
|
|
|
String roomId = sessionManager.getRoomId(session);
|
|
|
|
|
|
|
|
|
|
|
|
if (userId == null || roomId == null) {
|
|
|
|
|
|
sendError(session, "未加入房间");
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
log.info("[WS] 收到消息, roomId={}, userId={}, payload={}", roomId, userId, payload);
|
|
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
|
JSONObject json = JSON.parseObject(payload);
|
|
|
|
|
|
String type = json.getString("type");
|
2026-06-24 09:50:01 +08:00
|
|
|
|
Object rawData = json.get("data");
|
|
|
|
|
|
JSONObject data = (rawData instanceof JSONObject) ? (JSONObject) rawData : null;
|
2026-06-23 10:55:06 +08:00
|
|
|
|
|
2026-06-24 09:50:01 +08:00
|
|
|
|
// 通过路由器查找处理器
|
|
|
|
|
|
WsMessageHandler handler = router.get(type);
|
|
|
|
|
|
if (handler == null) {
|
|
|
|
|
|
sendError(session, "未知消息类型: " + type);
|
|
|
|
|
|
return;
|
2026-06-23 10:55:06 +08:00
|
|
|
|
}
|
2026-06-24 09:50:01 +08:00
|
|
|
|
|
|
|
|
|
|
handler.handle(roomId, userId, data, sessionManager);
|
2026-06-23 10:55:06 +08:00
|
|
|
|
} catch (Exception e) {
|
|
|
|
|
|
log.error("[WS] 处理消息异常, roomId={}, userId={}", roomId, userId, e);
|
|
|
|
|
|
sendError(session, e.getMessage());
|
|
|
|
|
|
}
|
2026-06-23 10:49:23 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
@Override
|
2026-06-23 10:55:06 +08:00
|
|
|
|
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
|
|
|
|
|
|
String userId = sessionManager.getUserId(session);
|
|
|
|
|
|
String roomId = sessionManager.getRoomId(session);
|
|
|
|
|
|
log.info("[WS] 连接关闭, roomId={}, userId={}, sessionId={}, status={}",
|
|
|
|
|
|
roomId, userId, session.getId(), status);
|
|
|
|
|
|
|
|
|
|
|
|
if (userId != null && roomId != null) {
|
|
|
|
|
|
// 通知游戏服务玩家断开
|
|
|
|
|
|
gomokuGameService.handleDisconnect(roomId, userId, sessionManager);
|
|
|
|
|
|
}
|
|
|
|
|
|
sessionManager.removeSession(session);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// ==================== 辅助方法 ====================
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 解析 URL Query 参数
|
|
|
|
|
|
*/
|
|
|
|
|
|
private String getQueryParam(String query, String key) {
|
|
|
|
|
|
for (String param : query.split("&")) {
|
|
|
|
|
|
String[] pair = param.split("=", 2);
|
|
|
|
|
|
if (pair.length == 2 && pair[0].equals(key)) {
|
|
|
|
|
|
return pair[1];
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
return null;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-06-23 14:32:19 +08:00
|
|
|
|
/** 聊天消息最大长度 */
|
|
|
|
|
|
private static final int CHAT_MAX_LENGTH = 500;
|
|
|
|
|
|
|
2026-06-23 10:55:06 +08:00
|
|
|
|
/**
|
|
|
|
|
|
* 聊天消息处理(暂不持久化,直接广播)
|
2026-06-23 14:32:19 +08:00
|
|
|
|
*
|
|
|
|
|
|
* 校验规则:
|
|
|
|
|
|
* - content 不能为 null 或空字符串
|
|
|
|
|
|
* - content 长度不能超过 CHAT_MAX_LENGTH(500 字符)
|
|
|
|
|
|
* - 移除 HTML 标签防止 XSS
|
2026-06-23 10:55:06 +08:00
|
|
|
|
*/
|
|
|
|
|
|
private void handleChat(String roomId, String userId, String content) {
|
2026-06-23 14:32:19 +08:00
|
|
|
|
// 内容为空或超长时直接丢弃
|
|
|
|
|
|
if (content == null || content.isBlank()) {
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
if (content.length() > CHAT_MAX_LENGTH) {
|
|
|
|
|
|
content = content.substring(0, CHAT_MAX_LENGTH);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 简易 XSS 防护:移除 HTML 标签
|
|
|
|
|
|
String sanitized = content
|
|
|
|
|
|
.replace("<", "<")
|
|
|
|
|
|
.replace(">", ">");
|
|
|
|
|
|
|
2026-06-23 10:55:06 +08:00
|
|
|
|
// TODO: 后续可增加消息持久化
|
|
|
|
|
|
broadcastToRoom(roomId, new WsMessage(WsOutboundMessage.CHAT_BROADCAST, Map.of(
|
|
|
|
|
|
"userId", userId,
|
2026-06-23 14:32:19 +08:00
|
|
|
|
"content", sanitized,
|
2026-06-23 10:55:06 +08:00
|
|
|
|
"timestamp", System.currentTimeMillis()
|
|
|
|
|
|
)));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 向房间内所有会话广播消息
|
|
|
|
|
|
*/
|
|
|
|
|
|
private void broadcastToRoom(String roomId, WsMessage message) {
|
|
|
|
|
|
String json = JSON.toJSONString(message);
|
|
|
|
|
|
for (WebSocketSession ws : sessionManager.getRoomSessions(roomId)) {
|
|
|
|
|
|
if (ws.isOpen()) {
|
|
|
|
|
|
try {
|
|
|
|
|
|
ws.sendMessage(new TextMessage(json));
|
|
|
|
|
|
} catch (IOException e) {
|
|
|
|
|
|
log.error("[WS] 发送消息失败, sessionId={}", ws.getId(), e);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 向指定会话发送错误消息
|
|
|
|
|
|
*/
|
|
|
|
|
|
private void sendError(WebSocketSession session, String errorMsg) {
|
|
|
|
|
|
if (session.isOpen()) {
|
|
|
|
|
|
try {
|
|
|
|
|
|
String json = JSON.toJSONString(
|
|
|
|
|
|
new WsMessage(WsOutboundMessage.ERROR, Map.of("message", errorMsg)));
|
|
|
|
|
|
session.sendMessage(new TextMessage(json));
|
|
|
|
|
|
} catch (IOException e) {
|
|
|
|
|
|
log.error("[WS] 发送错误消息失败", e);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-06-23 10:49:23 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|