폴링, 롱 폴링 및 SSE
데이터를 전송하는 폴링과 롱 폴링 같은 기존 방식과 서버 전송 이벤트를 비교하고 차이점을 이해합니다.
폴링, 롱 폴링 및 SSE은(는) CoddyKit의 무료 WebSockets & Realtime Systems Programming 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 WebSockets & Realtime Systems Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. WebSockets & Realtime Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
HTTP's Realtime Challenge
HTTP is stateless and unidirectional: the client asks, the server answers once. For live chat or tickers, constant asking or waiting is inefficient.
Introducing Polling
Polling is the simplest pseudo-realtime trick: the client asks the server for new data on a fixed interval, getting updates or an empty reply each time.
Polling Code Example
Here's a JavaScript client that polls a server every 2 seconds for updates — open your console to watch it fire.
<!DOCTYPE html>
<html>
<head>
<title>Polling Example</title>
</head>
<body>
<h1>Polling Status: <span id="status">Waiting...</span></h1>
<script>
function fetchData() {
// In a real app, this would be a server endpoint
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(data => {
const statusElement = document.getElementById('status');
statusElement.innerText = `Update at ${new Date().toLocaleTimeString()}`;
console.log('Polled:', data.title);
})
.catch(error => console.error('Polling error:', error));
}
// Poll every 2 seconds (2000 milliseconds)
setInterval(fetchData, 2000);
fetchData(); // Initial fetch to start
</script>
</body>
</html>Polling's Inefficiency
Polling is wasteful: high latency between polls, many empty responses burning resources, and poor scaling when many clients poll often.
Enter Long Polling
Long polling is smarter: instead of replying empty, the server holds the request open until data is ready or it times out, then the client reconnects.
How Long Polling Works
The long polling cycle: client requests, server waits for data or timeout, server responds and closes, client immediately re-requests to restart.
Long Polling Client Logic
Here's the long polling client pattern: it processes each response, then immediately reopens the connection (retrying after a delay on error).
function longPoll() {
console.log('Long polling for updates...');
fetch('/api/longpoll') // Imagine this endpoint holds the request
.then(response => response.json())
.then(data => {
if (data && data.message) {
console.log('Received update:', data.message);
// In a real app, update UI here
} else {
console.log('No new data, server likely timed out or sent empty.');
}
longPoll(); // Immediately send a new request
})
.catch(error => {
console.error('Long polling error:', error);
// Retry after a delay on error to prevent flooding
setTimeout(longPoll, 3000);
});
}
longPoll(); // Start the long polling processLong Polling's Pros & Cons
Long polling cuts latency and request count versus plain polling, but it still rides the request-response model — each update sets up and tears down a connection.
Server-Sent Events (SSE)
Server-Sent Events (SSE) give true server push over one long-lived HTTP connection. It's one-way (server to client) — perfect for feeds, tickers, notifications.
SSE Client Example
The native EventSource API makes subscribing to an SSE stream easy — the connection stays open until you close it or an error hits.
<!DOCTYPE html>
<html>
<head>
<title>SSE Example</title>
</head>
<body>
<h1>SSE Updates:</h1>
<ul id="events"></ul>
<script>
// Imagine a server at /sse-stream sending events
const eventSource = new EventSource('https://example.com/sse-stream'); // Replace with a real SSE endpoint
eventSource.onopen = () => {
console.log('SSE connection opened.');
const listItem = document.createElement('li');
listItem.textContent = `Connection opened at ${new Date().toLocaleTimeString()}`;
document.getElementById('events').appendChild(listItem);
};
eventSource.onmessage = (event) => {
const listItem = document.createElement('li');
listItem.textContent = `New message: ${event.data}`;
document.getElementById('events').appendChild(listItem);
console.log('Received SSE message:', event.data);
};
eventSource.onerror = (error) => {
console.error('SSE Error:', error);
const listItem = document.createElement('li');
listItem.textContent = `Error: ${error.message || 'Unknown'}`;
document.getElementById('events').appendChild(listItem);
eventSource.close(); // Close connection on error
};
// You can also listen for custom named events:
// eventSource.addEventListener('myCustomEvent', (event) => {
// console.log('Custom event data:', event.data);
// });
</script>
</body>
</html>Quick Check: Compare Methods
Which of the following statements about Polling, Long Polling, and Server-Sent Events (SSE) are true?
Recap: Unidirectional Push
Recap: polling repeatedly asks (simple but wasteful), long polling holds the request open, and SSE pushes one-way over a persistent connection.
자주 묻는 질문
“폴링, 롱 폴링 및 SSE” 강의는 무료인가요?
네 — “폴링, 롱 폴링 및 SSE” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Realtime Systems Programming 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Realtime Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
“폴링, 롱 폴링 및 SSE”에서 뭘 배우나요?
데이터를 전송하는 폴링과 롱 폴링 같은 기존 방식과 서버 전송 이벤트를 비교하고 차이점을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Realtime Systems Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
WebSockets & Realtime Systems Programming을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 WebSockets & Realtime Systems Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“폴링, 롱 폴링 및 SSE” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 WebSockets & Realtime Systems Programming 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 WebSockets & Realtime Systems Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 웹 통신의 발전
- 폴링, 롱 폴링 및 SSE
- WebSockets 소개: 새로운 시대
- 적합한 실시간 기술 선택하기