4 回答

TA貢獻1895條經驗 獲得超3個贊
您還可以使用org.springframework.messaging.simp.user.SimpUserRegistry;
將其注入您的控制器或服務
@Autowired
SimpUserRegistry simpUserRegistry;
然后在方法中創建邏輯,您可以simpUserRegistry.findSubscriptions(matcher)像這樣調用:
public Set<SimpSubscription> onlineUsers(String chatroomId) {
if(null == chatroomId || StringUtils.isEmpty(chatroomId)) {
return findSubscriptions("");
}
Set<SimpSubscription> subscriptions = new HashSet<>();
List<String> list = chatRoomService.listUserIdsInChatRoom(chatroomId);
for (String userId: list) {
subscriptions.addAll(findSubscriptions(userId));
}
return subscriptions;
}
public Set<SimpSubscription> findSubscriptions(String userId) {
return simpUserRegistry.findSubscriptions(new SimpSubscriptionMatcher() {
@Override
public boolean match(SimpSubscription subscription) {
return StringUtils.isEmpty(userId) ? true : subscription.getDestination().contains(userId);
}
});
}
它實際上是做什么的,它獲取所有在線用戶并將它們與您的特定 userId 進行匹配,如果 chatroomId 為空,它將為您獲取所有聊天室的所有在線用戶。

TA貢獻1865條經驗 獲得超7個贊
實現ApplicationListener<SessionDisconnectEvent>
并覆蓋了下面的方法。
@Override ?????public?void?onApplicationEvent(SessionDisconnectEvent?event)?{ ?????}
通過這種方式,我可以捕獲哪個用戶與 websocket 連接斷開。我仍在等待您的最佳實踐建議..

TA貢獻1835條經驗 獲得超7個贊
SessionConnectedEvent
?— 當代理發送 STOMP CONNECTED 幀以響應 CONNECT 時,在 SessionConnectEvent 之后不久發布。此時可以認為STOMP會話完全建立。SessionDisconnectEvent
?— STOMP 會話結束時發布。DISCONNECT 可能是從客戶端發送的,也可能是在 WebSocket 會話關閉時自動生成的。在某些情況下,每個會話可能會多次發布此事件。組件對于多個斷開事件應該是冪等的。
如果需要,您可以將在線用戶存儲在緩存中,并在相關用戶出入時通過 Websocket 將其在線狀態流式傳輸到客戶端。

TA貢獻1853條經驗 獲得超18個贊
使用會話 ID 來檢測用戶
SocketJS
this.client = over(new SockJS(environment.SOCKET+'/end'));
this.client.connect({userId:'UserIdHere'}, () => {
});
春季啟動
@Component
public class WebSocketEventListener {
private static final Logger logger = LoggerFactory.getLogger(WebSocketEventListener.class);
@Autowired
private SimpMessageSendingOperations messagingTemplate;
@EventListener
public void handleWebSocketConnectListener(SessionConnectedEvent event) {
StompHeaderAccessor stompAccessor = StompHeaderAccessor.wrap(event.getMessage());
@SuppressWarnings("rawtypes")
GenericMessage connectHeader = (GenericMessage) stompAccessor
.getHeader(SimpMessageHeaderAccessor.CONNECT_MESSAGE_HEADER); // FIXME find a way to pass the username
// to the server
@SuppressWarnings("unchecked")
Map<String, List<String>> nativeHeaders = (Map<String, List<String>>) connectHeader.getHeaders()
.get(SimpMessageHeaderAccessor.NATIVE_HEADERS);
String login = nativeHeaders.get("userId").get(0);
String sessionId = stompAccessor.getSessionId();
logger.info("Chat connection by user <{}> with sessionId <{}>", login, sessionId);
}
@EventListener
public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
StompHeaderAccessor stompAccessor = StompHeaderAccessor.wrap(event.getMessage());
String sessionId = stompAccessor.getSessionId();
logger.info("Chat connection by user <{}> with sessionId <{}>", "Nop", sessionId);
}
}
添加回答
舉報