0Pricing
WebSockets & Realtime Systems Programming · Lekcja

Cykl życia i stany połączenia

Poznają Państwo różne stany połączenia WebSocket — od otwierania po zamykanie — oraz sposoby zarządzania nimi.

Cykl życia i stany połączenia to bezpłatna lekcja WebSockets & Realtime Systems Programming na CoddyKit. To lekcja 3 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej WebSockets & Realtime Systems Programming, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs WebSockets & Realtime Systems Programming zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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.

Często zadawane pytania

Czy lekcja „Cykl życia i stany połączenia” jest bezpłatna?

Tak — pełny tekst „Cykl życia i stany połączenia” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu WebSockets & Realtime Systems Programming, przejdź na CoddyKit PRO. Kurs WebSockets & Realtime Systems Programming zawiera 4 lekcji w sumie.

Co nauczysz się w „Cykl życia i stany połączenia”?

Poznają Państwo różne stany połączenia WebSocket — od otwierania po zamykanie — oraz sposoby zarządzania nimi. Ćwiczysz WebSockets & Realtime Systems Programming z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć WebSockets & Realtime Systems Programming?

Nie wymagamy żadnego doświadczenia. WebSockets & Realtime Systems Programming w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 3 z 4.

Ile czasu zajmuje lekcja „Cykl życia i stany połączenia”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji WebSockets & Realtime Systems Programming?

Tak. Każda lekcja WebSockets & Realtime Systems Programming zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Jak działa handshake WebSocket
  2. Ramkowanie danych i komunikaty WebSocket
  3. Cykl życia i stany połączenia
  4. Podprotokoły, rozszerzenia i kompresja
← Powrót do WebSockets & Realtime Systems Programming