2
0

WebSocketDisconnectHandler.java 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * Copyright 2002-2016 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package sample.websocket;
  17. import org.springframework.context.ApplicationListener;
  18. import org.springframework.messaging.simp.SimpMessageSendingOperations;
  19. import org.springframework.web.socket.messaging.SessionDisconnectEvent;
  20. import sample.data.ActiveWebSocketUser;
  21. import sample.data.ActiveWebSocketUserRepository;
  22. import java.util.Arrays;
  23. /**
  24. * @author Rob Winch
  25. */
  26. public class WebSocketDisconnectHandler implements
  27. ApplicationListener<SessionDisconnectEvent> {
  28. private ActiveWebSocketUserRepository repository;
  29. private SimpMessageSendingOperations messagingTemplate;
  30. public WebSocketDisconnectHandler(SimpMessageSendingOperations messagingTemplate,
  31. ActiveWebSocketUserRepository repository) {
  32. super();
  33. this.messagingTemplate = messagingTemplate;
  34. this.repository = repository;
  35. }
  36. public void onApplicationEvent(SessionDisconnectEvent event) {
  37. String id = event.getSessionId();
  38. if (id == null) {
  39. return;
  40. }
  41. ActiveWebSocketUser user = repository.findOne(id);
  42. if (user == null) {
  43. return;
  44. }
  45. repository.delete(id);
  46. messagingTemplate.convertAndSend("/topic/friends/signout",
  47. Arrays.asList(user.getUsername()));
  48. }
  49. }