0Pricing
WebSockets & Realtime Systems Programming · 강의

연결 수명 주기와 상태

WebSocket 연결이 열림에서 닫힘으로 진행되는 다양한 상태와 이를 관리하는 방법을 살펴봅니다.

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

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

Understanding Connection States

When you work with WebSockets, it's crucial to know the current state of your connection. This helps you manage data flow and handle disconnections gracefully.

Just like a phone call goes through phases (dialing, connected, hanging up), a WebSocket connection has a defined lifecycle with specific states.

The CONNECTING State (0)

The very first state of a WebSocket is CONNECTING. This happens immediately after you create a new WebSocket object.

  • Its numeric value is 0.
  • In this state, the client is trying to establish a connection with the server.
  • This includes the initial HTTP handshake process that upgrades the connection to WebSocket.
  • You cannot send messages yet.

Connecting with Node.js

When a WebSocket client attempts to connect, it enters the CONNECTING state (readyState = 0). This is where the initial handshake occurs.

To run this Node.js example:

  1. Make sure you have Node.js installed.
  2. Open your terminal and run npm init -y
  3. Install the ws library: npm install ws
  4. Save the code below as index.js.
  5. Run node index.js.

Note: You'll need a WebSocket server running on ws://localhost:8080 for a successful connection.

const WebSocket = require('ws');

const ws = new WebSocket('ws://localhost:8080');

console.log(`Initial state: ${ws.readyState}`); // Expected: 0 (CONNECTING)

ws.onopen = () => {
  console.log(`Connection opened! State: ${ws.readyState}`); // Expected: 1 (OPEN)
  ws.send('Hello from CoddyKit client!');
  setTimeout(() => ws.close(1000, 'Demo complete'), 2000);
};

ws.onmessage = (event) => {
  console.log(`Received: ${event.data}`);
};

ws.onclose = (event) => {
  console.log(`Connection closed. Code: ${event.code}, Reason: ${event.reason}`);
  console.log(`Final state: ${ws.readyState}`); // Expected: 3 (CLOSED)
};

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

The OPEN State (1)

Once the handshake is complete and the connection is successfully established, the WebSocket enters the OPEN state.

  • Its numeric value is 1.
  • In this state, the connection is ready for bidirectional communication.
  • You can send data to the server, and the server can send data to you.
  • This is the active communication phase.

Handling the OPEN Event

The onopen event is fired once the WebSocket connection transitions from CONNECTING to OPEN. This is your cue that you can start sending messages.

Run this Node.js example to see the onopen event in action:

const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:8080');

ws.onopen = () => {
  console.log('WebSocket connection is now OPEN!');
  console.log(`Current state: ${ws.readyState}`); // Expected: 1 (OPEN)
  ws.send('Ready to chat!');
  setTimeout(() => ws.close(), 1500); // Close after a short delay
};

ws.onmessage = (event) => {
  console.log('Received:', event.data);
};

ws.onclose = () => {
  console.log('Connection closed.');
};

ws.onerror = (error) => {
  console.error('Error:', error.message);
};

The CLOSING State (2)

When either the client or the server decides to terminate the connection, it enters the CLOSING state.

  • Its numeric value is 2.
  • This state occurs after ws.close() is called, but before the connection is fully shut down.
  • During this phase, a closing handshake is performed to ensure a clean termination.
  • No new messages should be sent, though some buffered messages might still be processed.

Gracefully Closing a Connection

You can explicitly close a WebSocket connection using the ws.close() method. This will transition the connection through the CLOSING state (readyState = 2) before finally becoming CLOSED (readyState = 3).

Observe the state changes when closing:

const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:8080');

ws.onopen = () => {
  console.log(`Connection OPEN. State: ${ws.readyState}`); // 1
  console.log('Initiating connection close...');
  ws.close(1000, 'Client requested shutdown'); // Code 1000: normal closure
  console.log(`State after calling close(): ${ws.readyState}`); // Expected: 2 (CLOSING)
};

ws.onclose = (event) => {
  console.log(`Connection CLOSED. State: ${ws.readyState}`); // 3
  console.log(`Close Code: ${event.code}, Reason: ${event.reason}`);
};

ws.onerror = (error) => {
  console.error('Error during connection:', error.message);
};

The CLOSED State (3)

The final state for a WebSocket connection is CLOSED.

  • Its numeric value is 3.
  • The connection has been completely terminated.
  • No further communication can occur on this particular WebSocket object.
  • If you need to reconnect, you must create a new WebSocket instance.

Checking Connection Status

You can always check the current state of a WebSocket connection using its readyState property. This property returns one of the numeric values (0, 1, 2, 3) or their corresponding named constants:

  • WebSocket.CONNECTING (0)
  • WebSocket.OPEN (1)
  • WebSocket.CLOSING (2)
  • WebSocket.CLOSED (3)

Using these constants makes your code more readable!

Quick Check: Connection States

The readyState property indicates the current status of a WebSocket connection.

Recap: WebSocket Lifecycle

Great job! You've learned about the four essential states of a WebSocket connection:

  • CONNECTING (0): Handshake in progress.
  • OPEN (1): Connection established, ready for data.
  • CLOSING (2): Close handshake initiated.
  • CLOSED (3): Connection terminated.

Understanding these states is fundamental for building robust and reliable realtime applications.

자주 묻는 질문

“연결 수명 주기와 상태” 강의는 무료인가요?

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

“연결 수명 주기와 상태”에서 뭘 배우나요?

WebSocket 연결이 열림에서 닫힘으로 진행되는 다양한 상태와 이를 관리하는 방법을 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Realtime Systems Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“연결 수명 주기와 상태” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

  1. WebSocket 핸드셰이크 해설
  2. WebSocket 데이터 프레이밍과 메시지
  3. 연결 수명 주기와 상태
  4. 하위 프로토콜, 확장 기능 및 압축
← WebSockets & Realtime Systems Programming(으)로 돌아가기