WebSockets 및 실시간 기능
대화형 경험을 제공하는 Cloudflare Workers와 WebSockets를 사용하여 실시간 애플리케이션을 구현합니다.
WebSockets 및 실시간 기능은(는) CoddyKit의 무료 Edge Computing with Cloudflare Workers & Deno 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Edge Computing with Cloudflare Workers & Deno 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Edge Computing with Cloudflare Workers & Deno 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Real-time Apps with WebSockets
What are WebSockets? They enable real-time, two-way communication between a client (like your browser) and a server. Unlike traditional HTTP requests, WebSockets keep a persistent connection open.
This is perfect for applications needing instant updates, like chat apps, live dashboards, or online games.
HTTP vs. WebSocket Connection
Traditional HTTP is stateless and request-response based. Each action needs a new request from the client.
WebSockets, however, establish a single, long-lived connection. Once open, both client and server can send messages anytime without waiting for a request.
- HTTP: Client requests, server responds, connection closes.
- WebSocket: Client requests upgrade, server approves, connection stays open.
The WebSocket Upgrade
Before a WebSocket connection is established, an initial HTTP request is made. The client sends an "Upgrade" header, indicating its desire to switch protocols.
If the server supports WebSockets, it responds with an "101 Switching Protocols" status code, upgrading the connection from HTTP to WebSocket protocol. This is known as the WebSocket Handshake.
Cloudflare Workers & WebSockets
Cloudflare Workers are ideal for handling WebSockets at the edge. They can act as the server endpoint, managing connections and processing real-time messages directly where your users are.
Workers provide a WebSocketPair API to easily upgrade an incoming HTTP request into a WebSocket connection, simplifying the handshake process.
Worker WebSocket Upgrade
Let's create a Worker that accepts an incoming WebSocket connection. We'll use new WebSocketPair() to manage the connection.
Try running this example. To test, you'd typically connect using a WebSocket client (e.g., a browser's developer console or a dedicated tool).
export default {
async fetch(request) {
const upgradeHeader = request.headers.get('Upgrade');
if (!upgradeHeader || upgradeHeader !== 'websocket') {
return new Response('Expected Upgrade: websocket', { status: 426 });
}
const { 0: client, 1: server } = new WebSocketPair();
server.accept(); // Accept the WebSocket connection
server.addEventListener('message', event => {
console.log('Received message:', event.data);
// We'll add logic to send messages back soon!
});
server.addEventListener('close', event => {
console.log('WebSocket closed:', event.code, event.reason);
});
server.addEventListener('error', event => {
console.error('WebSocket error:', event.message);
});
return new Response(null, {
status: 101,
webSocket: client,
});
},
};WebSocket Event Listeners
Once a WebSocket connection is established, you can listen for various events on the server-side WebSocket object:
'open': Connection successfully established.'message': A message is received from the client. The message data is inevent.data.'close': The connection is closed by either side.'error': An error occurred on the connection.
These allow your Worker to react dynamically to client interactions.
Echoing Messages
In the previous code, we added an event listener for 'message'. Let's extend it to ensure the Worker echoes back any message it receives.
The server.send(message) method allows the Worker to send data back to the connected client. This creates a simple "echo" server.
export default {
async fetch(request) {
const upgradeHeader = request.headers.get('Upgrade');
if (!upgradeHeader || upgradeHeader !== 'websocket') {
return new Response('Expected Upgrade: websocket', { status: 426 });
}
const { 0: client, 1: server } = new WebSocketPair();
server.accept();
server.addEventListener('message', event => {
const message = event.data;
console.log('Received message:', message);
// Echo the message back to the client
server.send(`Echo from Worker: ${message}`);
});
server.addEventListener('close', event => {
console.log('WebSocket closed');
});
server.addEventListener('error', event => {
console.error('WebSocket error:', event);
});
return new Response(null, {
status: 101,
webSocket: client,
});
},
};Real-time Broadcasting
An echo server is a good start, but many real-time apps need to send messages to multiple connected clients (broadcasting).
For example, in a chat application, when one user sends a message, all other users in the chat room should receive it.
Cloudflare Workers, being stateless by default, need a mechanism to manage these connections across requests. This is where Durable Objects become incredibly useful for maintaining state and managing multiple WebSocket connections for a shared resource.
(We'll explore Durable Objects in a later lesson!)
Securing WebSockets
Just like HTTP, WebSocket connections should be secured. Always use wss:// (WebSocket Secure) instead of ws://.
wss:// connections are encrypted using TLS/SSL, preventing eavesdropping and tampering. Cloudflare Workers handle TLS termination automatically, so your connections are secured by default when deployed.
- Use
wss://for production. - Implement authentication/authorization.
- Validate all incoming messages.
Check Your Understanding
Consider a Cloudflare Worker that aims to establish a WebSocket connection with a client.
Recap: WebSockets at the Edge
Great job! You've learned how to implement real-time communication with WebSockets using Cloudflare Workers.
- WebSockets enable persistent, two-way communication.
- Workers use
WebSocketPairand101 Switching Protocolsfor the handshake. - Event listeners (
'message','close','error') manage connection lifecycle. - Always use
wss://for secure connections.
In future lessons, we'll dive into Durable Objects to manage state across multiple WebSocket connections for advanced real-time applications.
자주 묻는 질문
“WebSockets 및 실시간 기능” 강의는 무료인가요?
네 — “WebSockets 및 실시간 기능” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Edge Computing with Cloudflare Workers & Deno 강의 전체를 잠금 해제할 수 있습니다. Edge Computing with Cloudflare Workers & Deno 강의에는 총 4개의 강의가 포함되어 있습니다.
“WebSockets 및 실시간 기능”에서 뭘 배우나요?
대화형 경험을 제공하는 Cloudflare Workers와 WebSockets를 사용하여 실시간 애플리케이션을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Edge Computing with Cloudflare Workers & Deno을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Edge Computing with Cloudflare Workers & Deno을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Edge Computing with Cloudflare Workers & Deno은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“WebSockets 및 실시간 기능” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Edge Computing with Cloudflare Workers & Deno 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Edge Computing with Cloudflare Workers & Deno 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- WebSockets 및 실시간 기능
- 대기열 및 비동기 작업
- 서비스 바인딩 및 통합
- Cron 트리거 및 예약된 워커