|
| 1 | +package org.bssm.attachit.global.security.socket; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 4 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 5 | +import lombok.RequiredArgsConstructor; |
| 6 | +import org.bssm.attachit.domain.attachment.domain.Attachment; |
| 7 | +import org.bssm.attachit.domain.attachment.exception.SocketIOException; |
| 8 | +import org.bssm.attachit.domain.attachment.service.GetAttachmentListService; |
| 9 | +import org.springframework.scheduling.annotation.Scheduled; |
| 10 | +import org.springframework.stereotype.Component; |
| 11 | +import org.springframework.web.socket.CloseStatus; |
| 12 | +import org.springframework.web.socket.TextMessage; |
| 13 | +import org.springframework.web.socket.WebSocketSession; |
| 14 | +import org.springframework.web.socket.handler.TextWebSocketHandler; |
| 15 | + |
| 16 | +import java.io.IOException; |
| 17 | +import java.util.List; |
| 18 | +import java.util.concurrent.ConcurrentHashMap; |
| 19 | + |
| 20 | +@Component |
| 21 | +@RequiredArgsConstructor |
| 22 | +public class WebSocketHandler extends TextWebSocketHandler { |
| 23 | + |
| 24 | + private final GetAttachmentListService getAttachmentListService; |
| 25 | + private static final ObjectMapper objectMapper = new ObjectMapper(); |
| 26 | + private static final ConcurrentHashMap<String, WebSocketSession> CLIENTS = new ConcurrentHashMap<>(); |
| 27 | + |
| 28 | + @Override |
| 29 | + public void afterConnectionEstablished(WebSocketSession session) throws RuntimeException { |
| 30 | + CLIENTS.put(session.getId(), session); |
| 31 | + } |
| 32 | + |
| 33 | + @Override |
| 34 | + public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws RuntimeException { |
| 35 | + CLIENTS.remove(session.getId()); |
| 36 | + } |
| 37 | + |
| 38 | + @Scheduled(fixedRate = 1000, initialDelay = 5000) |
| 39 | + public void sendAttachmentListToAllClients() throws JsonProcessingException { |
| 40 | + List<Attachment> attachmentList = getAttachmentListService.execute(); |
| 41 | + String jsonAttachments = objectMapper.writeValueAsString(attachmentList); |
| 42 | + TextMessage message = new TextMessage(jsonAttachments); |
| 43 | + CLIENTS.forEach((key, value) -> { |
| 44 | + try { |
| 45 | + value.sendMessage(message); |
| 46 | + } catch (IOException e) { |
| 47 | + throw SocketIOException.EXCEPTION; |
| 48 | + } |
| 49 | + }); |
| 50 | + } |
| 51 | +} |
0 commit comments