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

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

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

先决条件

创建 Web PubSub for Socket.IO 资源

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

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

    Deploy to Azure

  • 从 Azure 门户搜索栏搜索

    1. 转到 Azure 门户

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

      Screenshot of searching the Web PubSub for Socket.IO service in the Azure portal.

  • 从市场搜索

    1. 转到 Azure 门户

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

      Screenshot of the Web PubSub for Socket.IO service in the marketplace.

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

      Screenshot of the Web PubSub for Socket.IO service in the Azure portal.

使用 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 集成。

/*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. 键入你的中心名称并复制“客户端终结点”和“客户端路径”

    Screenshot of the Web PubSub for Socket.IO service in the Azure portal client endpoints blade.

运行应用

  1. 运行服务器应用:

    node server.js "<connection-string>"
    

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

    Screenshot of the Web PubSub for Socket.IO service in the Azure portal connection string blade.

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

    node client.js