LocationWebSocketHandler.java 1.87 KB
package com.diligrp.rider.websocket;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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;

@Component
@RequiredArgsConstructor
@Slf4j
public class LocationWebSocketHandler extends TextWebSocketHandler {

    private final LocationSessionRegistry sessionRegistry;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        Object cityIdObj = session.getAttributes().get("cityId");
        if (!(cityIdObj instanceof Long cityId)) {
            session.close(CloseStatus.NOT_ACCEPTABLE.withReason("缺少城市信息"));
            return;
        }
        sessionRegistry.register(cityId, session);
        log.debug("位置推送连接建立,sessionId={} cityId={}", session.getId(), cityId);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        if ("ping".equalsIgnoreCase(message.getPayload())) {
            session.sendMessage(new TextMessage("pong"));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        sessionRegistry.unregister(session);
        log.debug("位置推送连接关闭,sessionId={} code={}", session.getId(), status.getCode());
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        sessionRegistry.unregister(session);
        if (session.isOpen()) {
            session.close(CloseStatus.SERVER_ERROR);
        }
        log.warn("位置推送连接异常,sessionId={}", session.getId(), exception);
    }
}