0Pricing
WebSockets & Realtime Systems Programming · บทเรียน

พื้นฐาน API WebSocket ของเบราว์เซอร์

ใช้วัตถุ `WebSocket` ในตัวของ JavaScript เพื่อสร้างและจัดการการเชื่อมต่อฝั่งไคลเอนต์

พื้นฐาน API WebSocket ของเบราว์เซอร์ เป็นบทเรียน WebSockets & Realtime Systems Programming ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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!

คำถามที่พบบ่อย

บทเรียน “พื้นฐาน API WebSocket ของเบราว์เซอร์” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “พื้นฐาน API WebSocket ของเบราว์เซอร์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส WebSockets & Realtime Systems Programming ให้อัปเกรดเป็น CoddyKit PRO คอร์ส WebSockets & Realtime Systems Programming มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “พื้นฐาน API WebSocket ของเบราว์เซอร์”

ใช้วัตถุ `WebSocket` ในตัวของ JavaScript เพื่อสร้างและจัดการการเชื่อมต่อฝั่งไคลเอนต์ คุณปฏิบัติ WebSockets & Realtime Systems Programming ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน WebSockets & Realtime Systems Programming หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน WebSockets & Realtime Systems Programming บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “พื้นฐาน API WebSocket ของเบราว์เซอร์” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน WebSockets & Realtime Systems Programming นี้ได้ไหม

ได้ บทเรียน WebSockets & Realtime Systems Programming ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. พื้นฐาน API WebSocket ของเบราว์เซอร์
  2. การส่งและรับข้อมูล
  3. การจัดการเหตุการณ์ฝั่งไคลเอนต์
  4. การเชื่อมต่อใหม่อัตโนมัติบนไคลเอนต์
← กลับไปที่ WebSockets & Realtime Systems Programming