LocationWebSocketHandler.java
1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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);
}
}