Skip to main content
Version: 4.x

客户端初始化

一旦你拥有 installed Socket.IO 客户端库,你现在就可以初始化客户端了。完整的选项列表可以在 此处 中找到。

¥Once you have installed the Socket.IO client library, you can now init the client. The complete list of options can be found here.

tip

对于 TypeScript 用户,可以为事件提供类型提示。请检查 this

¥For TypeScript users, it is possible to provide type hints for the events. Please check this.

在下面的示例中,io 对象来自:

¥In the examples below, the io object comes either from:

  • <script> 导入

    ¥the <script> import

<script src="/socket.io/socket.io.js"></script>
  • ESM 导入

    ¥an ESM import

<script type="module">
import { io } from "https://cdn.socket.io/4.7.5/socket.io.esm.min.js";
</script>
  • NPM
const { io } = require("socket.io-client");

来自同一域

¥From the same domain

如果你的前端与你的服务器位于同一域中,你可以简单地使用:

¥If your front is served on the same domain as your server, you can simply use:

const socket = io();

服务器 URL 将从 window.location 对象中推导出来。

¥The server URL will be deduced from the window.location object.

来自不同的域

¥From a different domain

如果你的前端不是由与服务器相同的域提供服务,则必须传递服务器的 URL。

¥In case your front is not served from the same domain as your server, you have to pass the URL of your server.

const socket = io("https://server-domain.com");

在这种情况下,请确保在服务器上启用 跨域资源共享 (CORS)

¥In that case, please make sure to enable Cross-Origin Resource Sharing (CORS) on the server.

info

你可以使用 httpswss(分别为 httpws)。

¥You can use either https or wss (respectively, http or ws).

// the following forms are similar
const socket = io("https://server-domain.com");
const socket = io("wss://server-domain.com");
const socket = io("server-domain.com"); // only in the browser when the page is served over https (will not work in Node.js)

自定义命名空间

¥Custom namespace

在上面的示例中,客户端将连接到主命名空间。对于大多数用例来说,仅使用主命名空间就足够了,但你可以使用以下方式指定命名空间:

¥In the examples above, the client will connect to the main namespace. Using only the main namespace should be sufficient for most use cases, but you can specify the namespace with:

// same origin version
const socket = io("/admin");
// cross origin version
const socket = io("https://server-domain.com/admin");

你可以找到有关命名空间 此处 的更多详细信息。

¥You can find more details about namespaces here.

选项

¥Options

可用选项的完整列表可在 此处 中找到。

¥The complete list of available options can be found here.