Skip to content

Commit

Permalink
Improved update time when refreshing/connecting to websocket by cachi…
Browse files Browse the repository at this point in the history
…ng the last message and sending it upon connection from a client.
  • Loading branch information
tedyoung committed Feb 14, 2024
1 parent fa9a8f8 commit 23076f2
Showing 1 changed file with 13 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,31 +13,37 @@

import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class WebSocketBroadcaster extends TextWebSocketHandler implements Broadcaster {
private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketBroadcaster.class);

private final Map<String, WebSocketSession> sessionMap = new ConcurrentHashMap<>();
private Optional<TextMessage> currentTextMessage = Optional.empty();

@Override
public void sendCurrentTimer(EnsembleTimer ensembleTimer) {
String html = TimerToHtmlTransformer.htmlFor(ensembleTimer);
TextMessage textMessage = new TextMessage(html);
sessionMap.values().forEach(session -> {
try {
session.sendMessage(textMessage);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
currentTextMessage = Optional.of(textMessage);
sessionMap.values().forEach(session -> sendMessageViaWebSocket(session, textMessage));
}

@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
LOGGER.info("Websocket connection established, session ID: {}, session remote address: {}", session.getId(), session.getRemoteAddress());
sessionMap.put(session.getId(), session);
currentTextMessage.ifPresent(message -> sendMessageViaWebSocket(session, message));
}

private void sendMessageViaWebSocket(WebSocketSession session, TextMessage message) {
try {
session.sendMessage(message);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

@Override
Expand Down

0 comments on commit 23076f2

Please sign in to comment.