วงจรชีวิตและสถานะการเชื่อมต่อ
สำรวจสถานะต่าง ๆ ของการเชื่อมต่อ WebSocket ตั้งแต่การเปิดจนถึงการปิด และวิธีจัดการสถานะเหล่านั้น
วงจรชีวิตและสถานะการเชื่อมต่อ เป็นบทเรียน WebSockets & Realtime Systems Programming ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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:
- Make sure you have Node.js installed.
- Open your terminal and run
npm init -y - Install the
wslibrary:npm install ws - Save the code below as
index.js. - 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
WebSocketinstance.
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.
คำถามที่พบบ่อย
บทเรียน “วงจรชีวิตและสถานะการเชื่อมต่อ” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “วงจรชีวิตและสถานะการเชื่อมต่อ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส WebSockets & Realtime Systems Programming ให้อัปเกรดเป็น CoddyKit PRO คอร์ส WebSockets & Realtime Systems Programming มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “วงจรชีวิตและสถานะการเชื่อมต่อ”
สำรวจสถานะต่าง ๆ ของการเชื่อมต่อ WebSocket ตั้งแต่การเปิดจนถึงการปิด และวิธีจัดการสถานะเหล่านั้น คุณปฏิบัติ WebSockets & Realtime Systems Programming ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน WebSockets & Realtime Systems Programming หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน WebSockets & Realtime Systems Programming บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “วงจรชีวิตและสถานะการเชื่อมต่อ” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน WebSockets & Realtime Systems Programming นี้ได้ไหม
ได้ บทเรียน WebSockets & Realtime Systems Programming ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- อธิบายการจับมือของ WebSocket
- การจัดกรอบข้อมูลและข้อความของ WebSocket
- วงจรชีวิตและสถานะการเชื่อมต่อ
- โพรโทคอลย่อย ส่วนขยาย และการบีบอัด