快速入门:将 Web PubSub for Socket.IO 整合到应用中

本快速入门演示了如何为 Socket.IO 资源创建 Web PubSub 并将其快速合并到 Socket.IO 应用中,以简化开发、加快部署并在不增加复杂性的情况下实现可伸缩性。

本快速入门中展示的代码采用 CommonJS。 如果你要使用 ECMAScript 模块,请参阅使用 Socket.IO 和 Azure Web PubSub 聊天演示

重要

本文中出现的原始连接字符串仅用于演示目的。

连接字符串包括应用程序访问 Azure Web PubSub 服务所需的授权信息。 连接字符串中的访问密钥类似于服务的根密码。 在生产环境中,请始终保护访问密钥。 使用 Azure Key Vault 安全地管理和轮换密钥,并使用 WebPubSubServiceClient 对连接进行保护

避免将访问密钥分发给其他用户、对其进行硬编码或将其以纯文本形式保存在其他人可以访问的任何位置。 如果你认为访问密钥可能已泄露,请轮换密钥。

先决条件

创建 Web PubSub for Socket.IO 资源

若要为 Socket.IO 创建 Web PubSub,可以使用以下一键式按钮进行创建,或按照以下操作在 Azure 门户中进行搜索。

  • 使用以下按钮在 Azure 中为 Socket.IO 资源创建 Web PubSub

    部署到 Azure

  • 从 Azure 门户搜索栏搜索

    1. 转到 Azure 门户

    2. 在搜索栏中搜索“socket.io”,然后选择“Web PubSub for Socket.IO”

      在 Azure 门户中搜索适用于 Socket.IO 的 Web PubSub 的屏幕截图。

  • 从市场搜索

    1. 转到 Azure 门户

    2. 选择 Azure 门户左上角的“创建资源”按钮。 在搜索框中键入“socket.io”,然后按 Enter。 在搜索结果中选择“Web PubSub for Socket.IO”

      市场中适用于 Socket.IO 的 Web PubSub 的屏幕截图。

    3. 在弹出页面中单击“创建”

      Azure 门户中 Web PubSub for Socket.IO 服务的屏幕截图。

使用 Socket.IO 库和 Web PubSub for Socket.IO 发送消息

在以下步骤中,创建 Socket.IO 项目并与 Web PubSub for Socket.IO 集成。

初始化 Node 项目并安装所需的包

mkdir quickstart
cd quickstart
npm init
npm install @azure/web-pubsub-socket.io socket.io-client

编写服务器代码

创建 server.js 文件并添加以下代码,以创建 Socket.IO 服务器并与 Web PubSub for Socket.IO 集成。

本文中出现的原始连接字符串仅用于演示目的。 在生产环境中,请始终保护访问密钥。 使用 Azure Key Vault 安全地管理和轮换密钥,并使用 WebPubSubServiceClient 对连接进行保护

/*server.js*/
const { Server } = require("socket.io");
const { useAzureSocketIO } = require("@azure/web-pubsub-socket.io");

let io = new Server(3000);

// Use the following line to integrate with Web PubSub for Socket.IO
useAzureSocketIO(io, {
    hub: "Hub", // The hub name can be any valid string.
    connectionString: process.argv[2]
});

io.on("connection", (socket) => {
    // Sends a message to the client
    socket.emit("hello", "world");

    // Receives a message from the client
    socket.on("howdy", (arg) => {
        console.log(arg);   // Prints "stranger"
    })
});

编写客户端代码

创建 client.js 文件并添加以下代码,以将客户端与 Web PubSub for Socket.IO 连接。

/*client.js*/
const io = require("socket.io-client");

const socket = io("<web-pubsub-socketio-endpoint>", {
    path: "/clients/socketio/hubs/Hub",
});

// Receives a message from the server
socket.on("hello", (arg) => {
    console.log(arg);
});

// Sends a message to the server
socket.emit("howdy", "stranger")

使用 Web PubSub for Socket.IO 时,客户端需要 <web-pubsub-socketio-endpoint>path 才能连接到服务。 可以在 Azure 门户中找到 <web-pubsub-socketio-endpoint>path

  1. 转到 Web PubSub for Socket.IO 的“密钥”边栏选项卡

  2. 键入你的中心名称并复制“客户端终结点”和“客户端路径”

    Azure 门户客户端终结点边栏选项卡中适用于 Socket.IO 的 Web PubSub 屏幕截图。

运行应用

  1. 运行服务器应用:

    node server.js "<connection-string>"
    

    <connection-string> 是连接字符串,其中包含用于访问 Web PubSub for Socket.IO 资源的终结点和密钥。 还可在 Azure 门户中查找此连接字符串

    Azure 门户连接字符串边栏选项卡中适用于 Socket.IO 的 Web PubSub 屏幕截图。

  2. 在另一个终端中运行客户端应用:

    node client.js