跳到内容

Node.js 原生 WebSocket 客户端

🌐 Native WebSocket Client in Node.js

介绍

🌐 Introduction

自从 Node.js v21 起,WebSocket API 已通过 Undici 库得到增强,新增了内置的 WebSocket 客户端。这简化了 Node.js 应用的实时通信。在 Node.js v22.4.0 版本中,WebSocket API 已被标记为稳定,表明它已准备好用于生产环境。

🌐 Since Node.js v21, the WebSocket API has been enhanced using the Undici library, introducing a built-in WebSocket client. This simplifies real-time communication for Node.js applications. In Node.js v22.4.0 release, the WebSocket API was marked as stable, indicating it's ready for production use.

什么是 WebSocket

🌐 What is a WebSocket

WebSocket 是一种标准化的通信协议,能够在单一 TCP 连接上实现同时双向通信。它具备全双工或双向通信能力,这使其有别于 HTTP。WebSocket 通过使用 HTTP Upgrade 头来切换协议,从而实现与 HTTP 的兼容性。它允许服务器在没有初始请求的情况下向客户端推送内容,并保持连接以便持续交换消息,使其在实时数据传输中比 HTTP 轮询等替代方案具有更低的开销。WebSocket 通信通常通过 TCP 端口 443(加密)或 80(未加密)进行,有助于绕过对非 Web 连接的防火墙限制。该协议定义了自己的 URI 方案(ws:// 和 wss://),分别用于未加密和加密连接,并被所有主流浏览器支持。

原生 WebSocket 客户端

🌐 Native WebSocket Client

Node.js现在可以作为WebSocket client,无需依赖像 wssocket.io 这样的外部库来进行客户端连接。这使得Node.js应用能够直接发起和管理外部WebSocket连接,从而简化连接实时数据流或与其他WebSocket服务器交互等任务。用户现在可以使用标准的 new WebSocket() 构造函数创建WebSocket客户端连接。

🌐 Node.js can now act as a WebSocket client without relying on external libraries like ws or socket.io for client connections. This allows Node.js applications to initiate and manage outgoing WebSocket connections directly, streamlining tasks such as connecting to real-time data feeds or interacting with other WebSocket servers. Users can now create a websocket client connection with the standard new WebSocket() constructor.

基于上述内容,让我们添加更多实际示例来演示演示基本用例的新 WebSocket 客户端功能。

🌐 Building on the above, let's add more practical examples to demonstrate the new WebSocket client functionality that demonstrates basic use-cases.

基本连接和消息处理

🌐 Basic Connection and Message Handling

// Creates a new WebSocket connection to the specified URL.
const socket = new WebSocket('ws://localhost:8080');

// Executes when the connection is successfully established.
socket.addEventListener('open', event => {
  console.log('WebSocket connection established!');
  // Sends a message to the WebSocket server.
  socket.send('Hello Server!');
});

// Listen for messages and executes when a message is received from the server.
socket.addEventListener('message', event => {
  console.log('Message from server: ', event.data);
});

// Executes when the connection is closed, providing the close code and reason.
socket.addEventListener('close', event => {
  console.log('WebSocket connection closed:', event.code, event.reason);
});

// Executes if an error occurs during the WebSocket communication.
socket.addEventListener('error', error => {
  console.error('WebSocket error:', error);
});

发送和接收 JSON 数据

🌐 Sending and Receiving JSON Data

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

socket.addEventListener('open', () => {
  const data = { type: 'message', content: 'Hello from Node.js!' };
  socket.send(JSON.stringify(data));
});

socket.addEventListener('message', event => {
  try {
    const receivedData = JSON.parse(event.data);
    console.log('Received JSON:', receivedData);
  } catch (error) {
    console.error('Error parsing JSON:', error);
    console.log('Received data was:', event.data);
  }
});

上面的 javascript 代码演示了发送和接收 JSON 数据,这在 WebSocket 应用中很常见。它使用 JSON.stringify() 将 JavaScript 对象转换为 JSON 字符串进行发送,然后使用 JSON.parse() 将接收到的字符串转换回 JavaScript 对象。最后,它包含了 JSON 解析的错误处理。

🌐 The javascript code above demonstrates sending and receiving JSON data, which is common in WebSocket applications. It uses JSON.stringify() to convert JavaScript objects to JSON strings before sending. And converts the received string back to a JavaScript object with JSON.parse(). Finally, it includes error handling for JSON parsing.

这提供了减少依赖管理和提高兼容性的优势。开发者可以避免安装和维护额外的 WebSocket 客户端库。内置的实现符合现代网页标准,确保更好的互操作性。该增强功能侧重于 WebSocket 通信的客户端,使 Node.js 能够作为 WebSocket 客户端使用。

🌐 This offers reduced dependency management and improved compatibility. Developers can avoid installing and maintaining additional WebSocket client libraries. The built-in implementation aligns with modern web standards, ensuring better interoperability. The enhancement focuses on the client-side of WebSocket communication, enabling Node.js to act as a WebSocket client.

重要要理解

🌐 Important to Understand

Node.js v22 提供内置的原生 WebSocket 服务器实现。要创建一个可以接受来自浏览器或其他客户端的 WebSocket 连接的服务器,仍然需要使用像 wssocket.io 这样的库。这意味着,虽然 Node.js 现在可以轻松 连接 到 WebSocket 服务器,但要 成为 WebSocket 服务器,仍然需要依赖外部工具。

🌐 Node.js v22 does not provide a built-in native WebSocket server implementation. To create a WebSocket server that accepts incoming connections from web browsers or other clients, one still need to use libraries like ws or socket.io. This means that while Node.js can now easily connect to WebSocket servers, it still requires external tools to become a WebSocket server.

总结

🌐 In Summary

Node.js v22 使应用能够作为“客户端”无缝地与 WebSocket 服务器交互,但在 Node.js 中创建 WebSocket 服务器仍然依赖于现有的库。对于开发者在实现 Node.js 项目的实时通信时,理解这一区别至关重要。

🌐 Node.js v22 empowers applications to seamlessly interact with WebSocket servers as clients, but the creation of WebSocket servers within Node.js remains dependent on established libraries. This distinction is crucial for developers to understand when implementing real-time communication in their Node.js projects.