Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect that client has disconnected using websocket in spring mvc

I want to be able to detect when the user has lost connection with the server (closed tab, lost internet connection, etc.) I am using stompjs over Sockjs on my client and spring mvc websockets on my server.

How can i detect when the client has lost connection. Here is how i configure my websocket message brocket:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer {
    @Autowired
    private TaskScheduler scheduler;

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic").setHeartbeatValue(new long[]{10000, 10000}).setTaskScheduler(scheduler);
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/web").setAllowedOrigins("*").withSockJS();
    }
}

And here is my controller class that actualy handles the incoming socket messages:

@RestController
@CrossOrigin
public class WebMessagingController {

    @MessageMapping("/chat/message")
    public void newUserMessage(String json) throws IOException {
        messagesProcessor.processUserMessage(json);
    }
}

I know that if i would have used class that extends from TextWebSocketHandler i would have bean able to override methods that are being called on connection and disconnection of the client, but i don`t think this is going to work with sock-js client. Thank you.

like image 213
Dmytro Kostyushko Avatar asked Oct 25 '25 23:10

Dmytro Kostyushko


1 Answers

In addition to Artem's response, you can use @EventListener annotation in any spring bean:

@EventListener
public void onDisconnectEvent(SessionDisconnectEvent event) {
    LOGGER.debug("Client with username {} disconnected", event.getUser());
}
like image 57
gmode Avatar answered Oct 28 '25 05:10

gmode