๋ฐ˜์‘ํ˜•
์„ค๋ช…

์„œ๋ฒ„์—์„œ ํด๋ผ์ด์–ธํŠธ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์ˆ˜์‹ ํ•˜๋Š” ๋ฐฉ๋ฒ• (๋‹จ๋ฐฉํ–ฅ ํ†ต์‹ )
WebSocket ์˜ ๊ฒฝ์šฐ, ์„œ๋ฒ„ <-> ํด๋ผ์ด์–ธํŠธ ๊ฐ„ ์–‘๋ฐฉํ–ฅ ํ†ต์‹ ์„ ํ•˜์ง€๋งŒ, SSE ์˜ ๊ฒฝ์šฐ ๋‹จ๋ฐฉํ–ฅ ํ†ต์‹ ์„ ํ•จ!
๋”ฐ๋ผ์„œ ๊ฐ„๋‹จํ•œ ์•Œ๋ฆผ ์ „์†ก ๊ธฐ๋Šฅ ๊ฐœ๋ฐœ๋“ฑ์— ์ ํ•ฉํ•œ ๊ธฐ์ˆ 

 

๊ตฌํ˜„ ์˜ˆ์ œ 
// server-side

// case1) SseEmitter ์ด์šฉ
// https://tecoble.techcourse.co.kr/post/2022-10-11-server-sent-events/ ์ฐธ๊ณ  


// case2) WebFlux ์ด์šฉ 
// ...
@GetMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> sse() {
    return Flux.just("Server time: " + LocalDateTime.now())
            .doFinally(signalType -> {
                if (signalType == SignalType.CANCEL || signalType == SignalType.ON_COMPLETE) {
                    log.info("Closing SSE connection");
                }
            });

    ..
}
<!-- client-side --> 
<!-- server-side ์˜ case2) ๋ฐฉ์‹ ๋Œ€์‘ --> 

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>SSE TEST</title>
</head>
<body>
<h1>SSE TEST</h1>
<div id="sse-data"></div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>

  const eventSource = new EventSource("{server-side์ฃผ์†Œ}/sse");
  eventSource.onmessage = event => {
     $("#sse-data").append(event.data); // ์ด๋ถ€๋ถ„์„ ํ† ์ŠคํŠธ ํŒ์—… ํ˜•ํƒœ๋กœ ํ‘œํ˜„ํ•˜๋ฉด ๋จ!
  };

  eventSource.onerror = error => {
    console.error("SSE error:", error);
    eventSource.close();
  };
</script>
</body>
</html>
๋ฐ˜์‘ํ˜•

'๊ฐœ๋ฐœ > etc' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

Vault  (1) 2023.02.07
ํ—ฅ์‚ฌ๊ณ ๋‚  ์•„ํ‚คํ…์ฒ˜ (Hexagonal Architecture)  (2) 2022.09.25
JWT (JSON WEB TOKEN)  (0) 2021.12.22
Rest API  (0) 2021.06.02
HTTP๊ด€๋ จ (https, spdy, ajax, websocket)  (0) 2018.12.09

+ Recent posts