본문 바로가기

장 실습: 다시 연결해 놓친 알림을 받는 알림판

서버의 알림 기록으로 SSE를 재개하고, 중복 표시를 막은 뒤 서비스 워커로 화면의 틀을 보관합니다.

앞 글까지 배운 내용을 모아 봅니다. 이 장에서 만든 것들을 모아 알림판을 완성하세요.

이 실습을 마치면 다음을 할 수 있습니다.

  • 서버에 보관한 알림을 SSE로 다시 보내고 화면의 중복 표시를 막습니다.
  • 서비스 워커에 화면 파일을 보관해 서버가 꺼졌을 때도 알림판의 틀을 엽니다.

시작 상태

실시간 웹 통신까지 만든 trend-lab을 씁니다. Express와 ws가 설치되어 있고 server.mjs와 public 폴더의 realtime.html, render.js, sse.js, chat.js가 있는 상태입니다. 15장 첫 글의 index.html, styles.css, 서비스 워커를 등록하는 script.js, sw.js도 public에 남겨 둡니다. 기존 상품 API가 읽는 content/products.json은 15장 3편의 파일을 그대로 씁니다. 의존성 폴더가 없다면 trend-lab에서 npm install을 실행합니다. 서버는 같은 폴더에서 node server.mjs로 켜고 http://localhost:4100/realtime.html을 엽니다.

과제와 완성 조건

  • SSE 경로가 연결마다 가상의 알림을 만드는 대신, 서버의 notifications 배열을 씁니다. 연결되면 Last-Event-ID보다 번호가 큰 알림을 먼저 모두 보내고, 그 뒤로는 새 알림이 생길 때마다 보냅니다.
  • sse.js는 이미 반영한 번호 이하의 알림을 다시 그리지 않습니다.
  • 첫 글의 서비스 워커가 알림판의 HTML과 스크립트를 캐시해, 서버가 꺼져 있어도 화면의 틀이 열립니다. /api/로 시작하는 주소는 캐시하지 않습니다.

힌트: 연결마다 만든 send 함수를 Set에 모아 두면, 알림을 만드는 타이머가 연결된 모든 브라우저에 보낼 수 있습니다. 서비스 워커의 캐시 목록에는 실제로 있는 파일만 넣고, 버전을 올립니다.

단계별 체크포인트

단계할 일확인할 결과
1. 서버 기록을 여러 연결에 보내기알림 생성 타이머는 하나만 두고, 연결별 send 함수를 subscribers에 등록합니다.새로 연결한 브라우저도 서버 배열에 남은 알림을 번호순으로 받습니다.
2. 끊긴 동안의 알림과 중복 확인하기Last-Event-ID 뒤의 알림을 다시 보내고 브라우저에서는 마지막 번호 이하를 건너뜁니다.아래 임시 코드로 끊었다 다시 연결하면 기다리는 동안 생긴 알림이 나타나고 번호가 중복되지 않습니다.
3. 화면의 틀을 오프라인에서 열기서비스 워커의 캐시 목록에 알림판 파일을 넣고 버전을 올립니다.서버를 끄고 새로고침해도 제목과 채팅 폼이 보입니다. 알림 목록은 비어 있습니다.

완성 파일

완성 파일과 확인 결과 보기

기존 상품 API와 채팅을 유지하면서 알림 재전송과 화면 캐시를 합친 여섯 파일입니다. realtime.html은 render.js, sse.js, chat.js를 이 순서로 한 번씩 불러옵니다.

server.mjs
import express from 'express';
import WebSocket, { WebSocketServer } from 'ws';
import { readFile } from 'node:fs/promises';

const app = express();

app.use(express.static('public'));

app.get('/api/products', async (request, response) => {
  const text = await readFile('content/products.json', 'utf8');
  response.json(JSON.parse(text));
});

const notifications = [];
const subscribers = new Set();
let nextId = 43;

setInterval(() => {
  const notification = {
    id: nextId,
    message: `새 알림 ${nextId}`,
    createdAt: new Date().toISOString(),
  };
  nextId += 1;
  notifications.push(notification);
  if (notifications.length > 100) notifications.shift();

  for (const send of subscribers) {
    send(notification);
  }
}, 10_000);

app.get('/api/notifications', (request, response) => {
  const after = Number(request.query.after ?? 0);
  response.json(notifications.filter((notification) => notification.id > after));
});

app.get('/api/notifications/stream', (request, response) => {
  response.setHeader('Content-Type', 'text/event-stream');
  response.setHeader('Cache-Control', 'no-cache');
  response.setHeader('Connection', 'keep-alive');
  response.flushHeaders();

  const send = (notification) => {
    response.write(`id: ${notification.id}\n`);
    response.write('event: notification\n');
    response.write(`data: ${JSON.stringify(notification)}\n\n`);
  };

  const requestedLastId = Number(request.get('last-event-id') ?? 42);
  const lastId = Number.isSafeInteger(requestedLastId) && requestedLastId >= 0
    ? requestedLastId
    : 42;

  for (const notification of notifications) {
    if (notification.id > lastId) send(notification);
  }
  subscribers.add(send);

  const heartbeat = setInterval(() => {
    response.write(': keep-alive\n\n');
  }, 15_000);

  response.on('close', () => {
    clearInterval(heartbeat);
    subscribers.delete(send);
  });
});

const server = app.listen(4100, () => {
  console.log('http://localhost:4100 에서 실행 중');
});

const wss = new WebSocketServer({ server, path: '/chat' });
let nextMessageId = 1024;

wss.on('connection', (socket) => {
  socket.on('error', console.error);

  socket.on('message', (data) => {
    let message;
    try {
      message = JSON.parse(data.toString());
    } catch (error) {
      return;
    }

    if (typeof message !== 'object' || message === null) {
      return;
    }

    if (message.type === 'join' && typeof message.roomId === 'string') {
      socket.roomId = message.roomId;
      return;
    }

    if (message.type !== 'chat'
        || socket.roomId === undefined
        || typeof message.content !== 'string'
        || message.content.length === 0
        || message.content.length > 200) {
      return;
    }

    const outgoing = JSON.stringify({
      type: 'chat',
      messageId: `m-${nextMessageId}`,
      roomId: socket.roomId,
      content: message.content,
      sentAt: new Date().toISOString(),
    });
    nextMessageId += 1;

    for (const client of wss.clients) {
      if (client.readyState === WebSocket.OPEN && client.roomId === socket.roomId) {
        client.send(outgoing);
      }
    }
  });
});
public/sse.js
const events = new EventSource('/api/notifications/stream');

let lastId = 42;

events.addEventListener('notification', (event) => {
  const notification = JSON.parse(event.data);
  if (notification.id <= lastId) return;

  renderNotification(notification);
  lastId = notification.id;
});

events.onopen = () => {
  showConnectionState('연결됨');
};

events.onerror = () => {
  showConnectionState(events.readyState === EventSource.CLOSED
    ? '연결 종료'
    : '재연결 중');
};

function stopNotifications() {
  events.close();
}
public/sw.js
const CACHE_PREFIX = 'trend-lab-public-';
const CACHE_NAME = `${CACHE_PREFIX}v6`;
const urlsToCache = [
  '/', '/index.html', '/styles.css', '/script.js',
  '/realtime.html', '/render.js', '/sse.js', '/chat.js',
];
const publicPaths = new Set(urlsToCache);

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME).then(cache => cache.addAll(urlsToCache))
  );
});

self.addEventListener('fetch', event => {
  const url = new URL(event.request.url);
  if (event.request.method !== 'GET'
      || url.origin !== self.location.origin
      || url.search !== ''
      || !publicPaths.has(url.pathname)) {
    return;
  }

  event.respondWith((async () => {
    const cache = await caches.open(CACHE_NAME);
    const cached = await cache.match(event.request);
    if (cached) return cached;

    try {
      const response = await fetch(event.request);
      if (response.status === 200 && response.type === 'basic') {
        try {
          await cache.put(event.request, response.clone());
        } catch (error) {
          console.warn('공개 파일을 저장하지 못했습니다');
        }
      }
      return response;
    } catch (error) {
      if (event.request.mode === 'navigate') {
        return new Response('오프라인입니다. 연결 후 다시 시도하세요.', {
          status: 503,
          headers: { 'Content-Type': 'text/plain; charset=utf-8' },
        });
      }
      return Response.error();
    }
  })());
});

self.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(names => Promise.all(
      names.filter(name => name.startsWith(CACHE_PREFIX) && name !== CACHE_NAME)
        .map(name => caches.delete(name))
    ))
  );
});
public/realtime.html
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>알림판</title>
</head>
<body>
  <h1>알림판</h1>
  <p id="state">연결 전</p>
  <ul id="notifications"></ul>

  <h2>채팅</h2>
  <p id="chat-state">연결 전</p>
  <form id="chat-form">
    <input name="content" maxlength="200" aria-label="메시지" required>
    <button>보내기</button>
  </form>
  <ul id="messages"></ul>

  <script src="/render.js"></script>
  <script src="/sse.js"></script>
  <script src="/chat.js"></script>
</body>
</html>
public/render.js
const list = document.querySelector('#notifications');
const state = document.querySelector('#state');

function renderNotification(notification) {
  const item = document.createElement('li');
  item.textContent = `#${notification.id} ${notification.message}`;
  list.append(item);
}

function renderNotifications(notifications) {
  notifications.forEach(renderNotification);
}

function showConnectionState(text) {
  state.textContent = text;
}
public/chat.js
const messages = document.querySelector('#messages');
const chatForm = document.querySelector('#chat-form');
const chatState = document.querySelector('#chat-state');
let socket;

const delays = [1_000, 2_000, 5_000, 10_000, 30_000];
let attempt = 0;

function scheduleReconnect(connect) {
  const delay = delays[Math.min(attempt, delays.length - 1)];
  attempt += 1;
  setTimeout(connect, delay);
}

function resetReconnectDelay() {
  attempt = 0;
}

function renderMessage(message) {
  const item = document.createElement('li');
  item.textContent = message.content;
  messages.append(item);
}

function connect() {
  socket = new WebSocket(`ws://${location.host}/chat`);

  socket.addEventListener('open', () => {
    resetReconnectDelay();
    chatState.textContent = '채팅 연결됨';
    socket.send(JSON.stringify({ type: 'join', roomId: 'general' }));
  });

  socket.addEventListener('close', () => {
    chatState.textContent = '채팅 연결이 끊겼습니다. 다시 연결을 기다립니다.';
    scheduleReconnect(connect);
  });

  socket.addEventListener('message', (event) => {
    const message = JSON.parse(event.data);
    renderMessage(message);
  });
}

function sendChat(content) {
  if (socket.readyState !== WebSocket.OPEN) {
    return;
  }

  socket.send(JSON.stringify({ type: 'chat', content }));
}

chatForm.addEventListener('submit', (event) => {
  event.preventDefault();
  sendChat(chatForm.elements.content.value);
  chatForm.reset();
});

connect();

서버의 알림 타이머는 연결들과 같은 배열을 사용하고, SSE 경로는 저장된 알림을 보낸 뒤 새 알림을 구독합니다.

처음 연결한 브라우저는 헤더가 없으므로 저장된 알림을 모두 받습니다. 놓친 알림을 보내는 반복문과 subscribers.add(send) 사이에는 await가 없어서, 그 사이에 타이머가 끼어들어 알림이 빠지는 일이 없습니다.

완성 파일의 캐시 이름은 trend-lab-public-v6입니다. 이미 v6 이상을 썼다면 지금 쓰는 값보다 하나 큰 버전으로 바꿉니다. 첫 글의 연습 문제에서 about.html을 만들었다면 '/about.html'도 목록에 남겨 둡니다. /api/로 시작하는 주소는 목록에 없으므로 서비스 워커를 거치지 않습니다.

먼저 놓친 알림이 돌아오는지 확인합니다. 연결을 일부러 끊기 위해 SSE 경로의 response.flushHeaders(); 아래에 두 줄을 임시로 넣습니다. retry: 줄은 브라우저가 재접속하기 전에 기다릴 시간을 밀리초로 정하고, 둘째 줄은 25초 뒤에 서버가 응답을 끝내게 합니다.

server.mjs (확인용 임시 코드)
  response.write('retry: 15000\n\n');
  setTimeout(() => response.end(), 25_000);

서버를 다시 켠 뒤 realtime.html을 새로고침해 알림 목록과 마지막 번호를 초기화합니다. 25초 뒤 상태가 “재연결 중”으로 바뀌고 15초 동안 알림이 멈췄다가, 다시 “연결됨”이 되는 순간 그동안 생긴 알림이 곧바로 나타납니다. 목록의 번호가 하나도 건너뛰지 않으면 성공입니다. 확인이 끝나면 임시 코드 두 줄을 지웁니다.

다음으로 캐시를 확인합니다. http://localhost:4100을 한 번 연 뒤 탭을 모두 닫았다가 realtime.html을 다시 엽니다. 이제 서버를 끄고 새로고침해도 알림판의 제목과 채팅 폼이 보이고, 채팅 상태에는 연결이 끊겼다는 문구가 나타납니다. 알림 목록은 비어 있습니다. 캐시한 것은 화면의 틀뿐이기 때문입니다.

서비스 워커 단계는 맨 마지막에 합니다. 이 단계를 마친 뒤에는 sse.js나 chat.js를 고쳐도 캐시된 예전 파일이 나가므로, 고칠 때마다 sw.js의 버전을 올리고 탭을 모두 닫았다 열어야 합니다.

다를 때 먼저 볼 곳

증상먼저 볼 곳
다시 연결했는데 번호가 겹칩니다sse.js의 notification.id <= lastId 검사와 갱신 순서를 확인합니다.
브라우저마다 다른 알림이 만들어집니다연결별 알림 타이머를 지우고 하나의 notifications 배열을 쓰는지 확인합니다.
서버를 끄면 화면의 틀이 사라집니다먼저 온라인에서 서비스 워커 설치를 마쳤는지, 캐시 파일 이름이 실제 파일과 같은지 확인합니다.
스크립트를 고쳐도 옛 코드가 보입니다캐시 버전을 올리고 관련 탭을 모두 닫았다 열었는지 확인합니다.

더 해 보기

  • 알림판을 두 탭에서 열고 같은 번호가 같은 내용인지 확인합니다.
  • 첫 글의 소개 페이지를 만든 경우 캐시 목록에 남겨, 알림판과 소개 페이지가 함께 오프라인에서 열리는지 확인합니다.

이것으로 15장과 웹 입문 트랙을 마칩니다. 15장에서는 trend-lab 폴더 하나를 키우며, 서버가 꺼져도 열리는 PWA, 브라우저에서 컴파일된 코드를 실행하는 WebAssembly, 미리 만든 페이지와 API를 나누는 JAMstack, 그리고 폴링과 SSE, WebSocket으로 서버의 새 소식을 받는 실시간 통신을 차례로 붙여 보았습니다. 처음부터 다시 훑어보고 싶다면 웹 입문 교재의 목차로 돌아가세요.