Skip to main content
Version: 4.x

入门

¥Getting started

欢迎来到 Socket.IO 教程!

¥Welcome to the Socket.IO tutorial!

在本教程中,我们将创建一个基本的聊天应用。它几乎不需要 Node.JS 或 Socket.IO 的基础知识,因此它适合所有知识水平的用户。

¥In this tutorial we'll create a basic chat application. It requires almost no basic prior knowledge of Node.JS or Socket.IO, so it’s ideal for users of all knowledge levels.

介绍

¥Introduction

使用 LAMP (PHP) 等流行的 Web 应用堆栈编写聊天应用通常非常困难。它涉及轮询服务器以了解更改,跟踪时间戳,并且它比应有的速度要慢得多。

¥Writing a chat application with popular web applications stacks like LAMP (PHP) has normally been very hard. It involves polling the server for changes, keeping track of timestamps, and it’s a lot slower than it should be.

传统上,套接字是大多数实时聊天系统构建的解决方案,在客户端和服务器之间提供双向通信通道。

¥Sockets have traditionally been the solution around which most real-time chat systems are architected, providing a bi-directional communication channel between a client and a server.

这意味着服务器可以向客户端推送消息。每当你编写聊天消息时,服务器都会获取它并将其推送到所有其他连接的客户端。

¥This means that the server can push messages to clients. Whenever you write a chat message, the idea is that the server will get it and push it to all other connected clients.

如何使用本教程

¥How to use this tutorial

工具

¥Tooling

任何文本编辑器(从基本文本编辑器到完整的 IDE,如 VS Code)都足以完成本教程。

¥Any text editor (from a basic text editor to a complete IDE such as VS Code) should be sufficient to complete this tutorial.

此外,在每个步骤的末尾,你都会找到一些在线平台(即 CodeSandboxStackBlitz)的链接,允许你直接从浏览器运行代码:

¥Additionally, at the end of each step you will find a link to some online platforms (CodeSandbox and StackBlitz, namely), allowing you to run the code directly from your browser:

Screenshot of the CodeSandbox platform

语法设置

¥Syntax settings

在 Node.js 世界中,有两种导入模块的方法:

¥In the Node.js world, there are two ways to import modules:

  • 标准方式:ECMAScript 模块(或 ESM)

    ¥the standard way: ECMAScript modules (or ESM)

import { Server } from "socket.io";

参考:https://nodejs.cn/api/esm.html

¥Reference: https://nodejs.cn/api/esm.html

  • 传统方式:CommonJS

    ¥the legacy way: CommonJS

const { Server } = require("socket.io");

参考:https://nodejs.cn/api/modules.html

¥Reference: https://nodejs.cn/api/modules.html

Socket.IO 支持这两种语法。

¥Socket.IO supports both syntax.

tip

我们建议在你的项目中使用 ESM 语法,尽管由于某些包不支持此语法,这可能并不总是可行。

¥We recommend using the ESM syntax in your project, though this might not always be feasible due to some packages not supporting this syntax.

为了你的方便,在整个教程中,每个代码块都允许你选择你喜欢的语法:

¥For your convenience, throughout the tutorial, each code block allows you to select your preferred syntax:

const { Server } = require("socket.io");

准备好?单击 "下一个" 开始。

¥Ready? Click "Next" to get started.