Java Code Examples for org.springframework.web.socket.messaging.SessionDisconnectEvent

The following examples show how to use org.springframework.web.socket.messaging.SessionDisconnectEvent. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@EventListener
public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {

    StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());

    String username = (String) headerAccessor.getSessionAttributes().get("username");

    if(username != null) {
        LOGGER.info("User Disconnected : " + username);
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setType(ChatMessage.MessageType.LEAVE);
        chatMessage.setSender(username);
        try {
            redisTemplate.opsForSet().remove(onlineUsers, username);
            redisTemplate.convertAndSend(userStatus, JsonUtil.parseObjToJson(chatMessage));
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

    }
}
 
Example 2
Source Project: xechat   Source File: WebSocketEventListener.java    License: MIT License 6 votes vote down vote up
/**
 * 断开连接监听
 *
 * @param sessionDisconnectEvent
 */
@EventListener
public void handleDisconnectListener(SessionDisconnectEvent sessionDisconnectEvent) throws Exception {
    log.debug("断开连接 -> {}", sessionDisconnectEvent);

    String userId = sessionDisconnectEvent.getUser().getName();
    User user = UserCache.getUser(userId);
    if (null == user) {
        log.debug("用户不存在 uid ->", userId);
        return;
    }

    user.setStatus(UserStatusConstant.OFFLINE);
    UserCache.removeUser(userId);

    // 广播离线消息
    sendMessage(buildMessageVo(user, MessageConstant.OFFLINE_MESSAGE));
    log.debug("广播离线消息 -> {}", user);
}
 
Example 3
Source Project: code   Source File: WebSocketEventListener.java    License: Apache License 2.0 6 votes vote down vote up
@EventListener
public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {

    StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());

    String username = (String) headerAccessor.getSessionAttributes().get("username");

    if(username != null) {
        LOGGER.info("User Disconnected : " + username);
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setType(ChatMessage.MessageType.LEAVE);
        chatMessage.setSender(username);
        try {
            redisTemplate.opsForSet().remove(onlineUsers, username);
            redisTemplate.convertAndSend(userStatus, JsonUtil.parseObjToJson(chatMessage));
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

    }
}
 
Example 4
Source Project: kafka-webview   Source File: PresenceEventListenerTest.java    License: MIT License 6 votes vote down vote up
/**
 * Tests that we request to disconnect based on the session id.
 */
@Test
public void testDisconnectListner() {
    final String sessionId = "my-session-id";
    final SessionDisconnectEvent mockEvent = mock(SessionDisconnectEvent.class);
    when(mockEvent.getSessionId()).thenReturn(sessionId);

    // Create mock Manager
    final WebSocketConsumersManager mockManager = mock(WebSocketConsumersManager.class);

    // Create our listener
    final PresenceEventListener eventListener = new PresenceEventListener(mockManager);

    // Call method
    eventListener.handleSessionDisconnect(mockEvent);

    // validate
    verify(mockManager, times(1)).removeConsumersForSessionId(eq(sessionId));
}
 
Example 5
@EventListener
public void onSessionDisConnected(SessionDisconnectEvent event) {
    Message msg = event.getMessage();
    StompHeaderAccessor accessor = StompHeaderAccessor.wrap(msg);
    String sessionId = accessor.getSessionId();

    String spaceKey = (String) webSocketSessionStore.getAttribute(sessionId, "spaceKey");

    log.debug("Session disconnect: spaceKey => {}, sessionId => {} ", spaceKey, sessionId);

    if (spaceKey == null) {
        return;
    }

    onlineWorkspaceStore.removeSession(spaceKey, sessionId);
    boolean isToBeOffline = onlineWorkspaceStore.isEmpty(spaceKey);

    if (isToBeOffline) {
        eventPublisher.publishEvent(new WorkspaceOfflineEvent(event, spaceKey));
    }

}
 
Example 6
Source Project: bearchoke   Source File: WebSocketDisconnectHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
    public void onApplicationEvent(SessionDisconnectEvent event) {
        if (log.isDebugEnabled()) {
            log.debug("Caught Web Socket disconnect event");
        }

        String id = event.getSessionId();
        if (StringUtils.isBlank(id)) {
            return;
        }

        if (log.isDebugEnabled()) {
            log.debug("Current web socket session id: " + id);
        }

        ActiveWebSocketUser user = repository.findUserBySessionId(id);

        if (user == null) {
            return;
        }

        repository.delete(user.getId());

//        messagingTemplate.convertAndSend("/topic/friends/signout", Arrays.asList(user.getUsername()));
    }
 
Example 7
Source Project: code   Source File: WebSocketEventListener.java    License: Apache License 2.0 5 votes vote down vote up
@EventListener
public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
    StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());

    String username = (String) headerAccessor.getSessionAttributes().get("username");
    if(username != null) {
        logger.info("User Disconnected : " + username);
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setType(ChatMessage.MessageType.LEAVE);
        chatMessage.setSender(username);
        messagingTemplate.convertAndSend("/topic/public", chatMessage);
    }
}
 
Example 8
Source Project: alchemy   Source File: ActivityService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(SessionDisconnectEvent event) {
    ActivityDTO activityDTO = new ActivityDTO();
    activityDTO.setSessionId(event.getSessionId());
    activityDTO.setPage("logout");
    messagingTemplate.convertAndSend("/topic/tracker", activityDTO);
}
 
Example 9
Source Project: TeamDojo   Source File: ActivityService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(SessionDisconnectEvent event) {
    ActivityDTO activityDTO = new ActivityDTO();
    activityDTO.setSessionId(event.getSessionId());
    activityDTO.setPage("logout");
    messagingTemplate.convertAndSend("/topic/tracker", activityDTO);
}
 
Example 10
Source Project: kafka-webview   Source File: PresenceEventListener.java    License: MIT License 5 votes vote down vote up
/**
 * Called when a web socket disconnects.  We'll close out any consumers that web socket client had running
 * based on their sessionId.
 */
@EventListener
void handleSessionDisconnect(final SessionDisconnectEvent event) {
    // Grab sessionId from event
    final String sessionId = event.getSessionId();

    // Disconnect that sessionId's consumers
    webSocketConsumersManager.removeConsumersForSessionId(sessionId);
}
 
Example 11
Source Project: springboot-learn   Source File: WebSocketEventListener.java    License: MIT License 5 votes vote down vote up
@EventListener
public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
    StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());

    String username = (String) headerAccessor.getSessionAttributes().get("username");
    if (username != null) {
        logger.info("User Disconnected : " + username);

        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setType(ChatMessage.MessageType.LEAVE);
        chatMessage.setSender(username);

        messagingTemplate.convertAndSend(WebSocketConstants.CHAT_TOPIC, chatMessage);
    }
}
 
Example 12
@Override
public void onApplicationEvent(SessionDisconnectEvent event) {
    ActivityDTO activityDTO = new ActivityDTO();
    activityDTO.setSessionId(event.getSessionId());
    activityDTO.setPage("logout");
    messagingTemplate.convertAndSend("/topic/tracker", activityDTO);
}
 
Example 13
Source Project: gpmr   Source File: ActivityService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(SessionDisconnectEvent event) {
    ActivityDTO activityDTO = new ActivityDTO();
    activityDTO.setSessionId(event.getSessionId());
    activityDTO.setPage("logout");
    messagingTemplate.convertAndSend("/topic/tracker", activityDTO);
}
 
Example 14
Source Project: ServiceCutter   Source File: ActivityService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(SessionDisconnectEvent event) {
    ActivityDTO activityDTO = new ActivityDTO();
    activityDTO.setSessionId(event.getSessionId());
    activityDTO.setPage("logout");
    messagingTemplate.convertAndSend("/topic/tracker", activityDTO);
}
 
Example 15
Source Project: spring-session   Source File: WebSocketDisconnectHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(SessionDisconnectEvent event) {
	String id = event.getSessionId();
	if (id == null) {
		return;
	}
	this.repository.findById(id).ifPresent((user) -> {
		this.repository.deleteById(id);
		this.messagingTemplate.convertAndSend("/topic/friends/signout",
				Collections.singletonList(user.getUsername()));
	});
}
 
Example 16
@BeforeEach
void setup() {
	MockitoAnnotations.initMocks(this);
	String sessionId = "session-id";
	MapSession session = new MapSession(sessionId);

	this.attributes = new HashMap<>();
	SessionRepositoryMessageInterceptor.setSessionId(this.attributes, sessionId);

	given(this.wsSession.getAttributes()).willReturn(this.attributes);
	given(this.wsSession.getPrincipal()).willReturn(this.principal);
	given(this.wsSession.getId()).willReturn("wsSession-id");

	given(this.wsSession2.getAttributes()).willReturn(this.attributes);
	given(this.wsSession2.getPrincipal()).willReturn(this.principal);
	given(this.wsSession2.getId()).willReturn("wsSession-id2");

	Map<String, Object> headers = new HashMap<>();
	headers.put(SimpMessageHeaderAccessor.SESSION_ATTRIBUTES, this.attributes);
	given(this.message.getHeaders()).willReturn(new MessageHeaders(headers));

	this.listener = new WebSocketRegistryListener();
	this.connect = new SessionConnectEvent(this.listener, this.wsSession);
	this.connect2 = new SessionConnectEvent(this.listener, this.wsSession2);
	this.disconnect = new SessionDisconnectEvent(this.listener, this.message, this.wsSession.getId(),
			CloseStatus.NORMAL);
	this.deleted = new SessionDeletedEvent(this.listener, session);
	this.expired = new SessionExpiredEvent(this.listener, session);
}
 
Example 17
@Override
public void onApplicationEvent(final SessionDisconnectEvent event)
{
	final String sessionId = event.getSessionId();
	websocketProducersRegistry.onSessionDisconnect(sessionId);
}