你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
本快速入门演示了如何为 Socket.IO 资源创建 Web PubSub 并将其快速合并到 Socket.IO 应用中,以简化开发、加快部署并在不增加复杂性的情况下实现可伸缩性。
本快速入门中展示的代码采用 CommonJS。 如果你要使用 ECMAScript 模块,请参阅使用 Socket.IO 和 Azure Web PubSub 聊天演示。
重要
本文中出现的原始连接字符串仅用于演示目的。
连接字符串包括应用程序访问 Azure Web PubSub 服务所需的授权信息。 连接字符串中的访问密钥类似于服务的根密码。 在生产环境中,请始终保护访问密钥。 使用 Azure Key Vault 安全地管理和轮换密钥,并使用 WebPubSubServiceClient 对连接进行保护。
避免将访问密钥分发给其他用户、对其进行硬编码或将其以纯文本形式保存在其他人可以访问的任何位置。 如果你认为访问密钥可能已泄露,请轮换密钥。
先决条件
- 具有活动订阅的 Azure 帐户。 如果没有帐户,可以创建一个免费帐户。
- 对 Socket.IO 库有一定的了解。
创建 Web PubSub for Socket.IO 资源
若要为 Socket.IO 创建 Web PubSub,可以使用以下一键式按钮进行创建,或按照以下操作在 Azure 门户中进行搜索。
- 使用以下按钮在 Azure 中为 Socket.IO 资源创建 Web PubSub 
- 从 Azure 门户搜索栏搜索 - 转到 Azure 门户。 
- 在搜索栏中搜索“socket.io”,然后选择“Web PubSub for Socket.IO”。   
 
- 从市场搜索 - 转到 Azure 门户。 
- 选择 Azure 门户左上角的“创建资源”按钮。 在搜索框中键入“socket.io”,然后按 Enter。 在搜索结果中选择“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。
- 转到 Web PubSub for Socket.IO 的“密钥”边栏选项卡 
- 键入你的中心名称并复制“客户端终结点”和“客户端路径”   
运行应用
- 运行服务器应用: - node server.js "<connection-string>"- <connection-string>是连接字符串,其中包含用于访问 Web PubSub for Socket.IO 资源的终结点和密钥。 还可在 Azure 门户中查找此连接字符串  
- 在另一个终端中运行客户端应用: - node client.js