0Pricing
WebSockets & Realtime Systems Programming · 课时

浏览器 WebSocket API 基础

在 JavaScript 中使用原生的 `WebSocket` 对象建立并管理客户端连接。

浏览器 WebSocket API 基础 是 CoddyKit 上的免费 WebSockets & Realtime Systems Programming 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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 基础」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebSockets & Realtime Systems Programming 课程的其余内容,请升级到 CoddyKit PRO。 WebSockets & Realtime Systems Programming 课程共包含 4 节课。

「浏览器 WebSocket API 基础」这节课中我会学到什么?

在 JavaScript 中使用原生的 `WebSocket` 对象建立并管理客户端连接。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Realtime Systems Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 WebSockets & Realtime Systems Programming 需要有经验吗?

无需任何先前经验。CoddyKit 上的 WebSockets & Realtime Systems Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「浏览器 WebSocket API 基础」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 WebSockets & Realtime Systems Programming 课中编写并运行代码吗?

能。每节 WebSockets & Realtime Systems Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 浏览器 WebSocket API 基础
  2. 发送与接收数据
  3. 客户端事件处理
  4. 客户端自动重新连接
← 返回 WebSockets & Realtime Systems Programming