0Pricing
WebSockets & Realtime Systems Programming · 강의

브라우저 WebSocket API 기초

JavaScript의 기본 제공 `WebSocket` 객체를 사용하여 클라이언트 측 연결을 설정하고 관리합니다.

브라우저 WebSocket API 기초은(는) CoddyKit의 무료 WebSockets & Realtime Systems Programming 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 WebSockets & Realtime Systems Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. WebSockets & Realtime Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Browser WebSocket Power

Welcome to the world of real-time web! The browser's native WebSocket API is your direct link to instant data exchange.

It lets web pages talk to servers constantly, without needing to refresh. Imagine live chats, multiplayer game updates, or real-time stock tickers – all powered by WebSockets!

Initiating a WebSocket

To start, you create a new WebSocket object in JavaScript. You need the server's URL, which begins with ws:// for unsecure connections or wss:// for secure, encrypted ones (like https://).

const socket = new WebSocket("wss://echo.websocket.events");
console.log("WebSocket object created. Attempting connection...");

Understanding `readyState`

A WebSocket connection goes through different states, which you can check using the readyState property. This tells you the current status:

  • 0 (CONNECTING): The connection is not yet open.
  • 1 (OPEN): The connection is established and ready for communication.
  • 2 (CLOSING): The connection is in the process of closing.
  • 3 (CLOSED): The connection has been closed or could not be opened.

When Connection Opens

The onopen event fires when your WebSocket connection has successfully established. This is the perfect moment to confirm the connection and perhaps send your first message to the server!

const socket = new WebSocket("wss://echo.websocket.events");

socket.onopen = (event) => {
  console.log("Connection opened successfully!");
  // Now you can safely send data.
};

console.log("Waiting for WebSocket connection to open...");

Sending Data with `send()`

Once the connection is OPEN (i.e., after onopen fires), you can use the send() method to transmit data to the server. You can send strings, Blobs, or ArrayBuffers.

const socket = new WebSocket("wss://echo.websocket.events");

socket.onopen = () => {
  socket.send("Hello from CoddyKit!");
  console.log("Sent 'Hello from CoddyKit!' to server.");
};

socket.onerror = (error) => {
  console.error("Connection error before sending.");
};

console.log("WebSocket client ready to send a message...");

Handling Incoming Data

The onmessage event is triggered whenever the client receives data from the server. The actual data payload is available in event.data.

const socket = new WebSocket("wss://echo.websocket.events");

socket.onopen = () => {
  socket.send("Requesting echo...");
};

socket.onmessage = (event) => {
  console.log("Received data:", event.data);
  // A real echo server would send "Requesting echo..." back.
};

socket.onerror = (error) => {
  console.error("Connection error during message receipt.");
};

console.log("Listening for messages from the server...");

Graceful Disconnect: `close()`

To close a WebSocket connection gracefully, use the close() method. You can optionally provide a numeric code and a human-readable reason for the closure.

const socket = new WebSocket("wss://echo.websocket.events");

socket.onopen = () => {
  console.log("Connection open. Closing in 1 second...");
  setTimeout(() => {
    socket.close(1000, "Demo complete");
  }, 1000);
};

socket.onclose = (event) => {
  console.log(`Connection closed: Code ${event.code} - ${event.reason}`);
};

console.log("Attempting to open then close connection...");

Understanding `onclose` Details

The onclose event provides useful details about why the connection closed. The event object includes:

  • event.wasClean: A boolean indicating if the connection closed cleanly.
  • event.code: A numeric status code (e.g., 1000 for Normal Closure).
  • event.reason: A human-readable string explaining the closure.

These details help you debug and manage your connection's lifecycle.

Catching Connection Errors

Network issues, invalid server URLs, or server-side problems can cause a WebSocket connection to fail. The onerror event is crucial for catching these issues and reacting appropriately.

Note: The error object itself often provides limited details for security reasons, but its occurrence signals a problem.

const socket = new WebSocket("ws://nonexistent.server"); // Intentionally bad URL

socket.onerror = (error) => {
  console.error("WebSocket Error occurred!");
  // This typically fires before onclose for connection failures.
};

socket.onclose = (event) => {
  if (!event.wasClean) {
    console.log("Connection closed due to error or unclean shutdown.");
  }
};

console.log("Attempting connection to a non-existent server to trigger an error...");

Putting it All Together

Here's a conceptual look at how you might combine all these event handlers for a basic client flow:

const ws = new WebSocket("wss://echo.websocket.events");

ws.onopen = () => {
  console.log("Connected to server!");
  ws.send("Hello from client!");
};

ws.onmessage = (event) => {
  console.log("Server says:", event.data);
  ws.close(); // Close after receiving the first message
};

ws.onclose = (event) => {
  console.log(`Disconnected: ${event.code} - ${event.reason}`);
};

ws.onerror = (err) => {
  console.error("WebSocket Error:", err);
};

This structure ensures you react to all key stages of the connection.

WebSocket Quiz

Which of the following WebSocket API methods or properties is primarily used to send data from the client to the server?

Recap: WebSocket Fundamentals

Great job! You've successfully explored the essentials of the browser's native WebSocket API:

  • How to create a new WebSocket instance with new WebSocket().
  • Understanding connection states using the readyState property.
  • Handling crucial connection events: onopen, onmessage, onclose, and onerror.
  • Sending data to the server using the send() method.
  • Gracefully closing connections with close().

Next, we'll dive deeper into handling different types of data and managing client-side events more robustly to build truly interactive applications!

자주 묻는 질문

“브라우저 WebSocket API 기초” 강의는 무료인가요?

네 — “브라우저 WebSocket API 기초” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Realtime Systems Programming 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Realtime Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.

“브라우저 WebSocket API 기초”에서 뭘 배우나요?

JavaScript의 기본 제공 `WebSocket` 객체를 사용하여 클라이언트 측 연결을 설정하고 관리합니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Realtime Systems Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

WebSockets & Realtime Systems Programming을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 WebSockets & Realtime Systems Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“브라우저 WebSocket API 기초” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 WebSockets & Realtime Systems Programming 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 WebSockets & Realtime Systems Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 브라우저 WebSocket API 기초
  2. 데이터 송수신
  3. 클라이언트 측 이벤트 처리
  4. 클라이언트 자동 재연결
← WebSockets & Realtime Systems Programming(으)로 돌아가기