开始在 Node.js 中使用中继混合连接 WebSocket

在本快速入门中,请创建 Node.js 发送者和接收者应用程序,以便在 Azure 中继中通过混合连接 WebSocket 发送和接收消息。 若要了解 Azure 中继的常规信息,请参阅 Azure 中继

在本快速入门中,你将执行以下步骤:

  1. 使用 Azure 门户创建中继命名空间。
  2. 使用 Azure 门户在该命名空间中创建混合连接。
  3. 编写服务器(侦听器)控制台应用程序,用于接收消息。
  4. 编写客户端(发送方)控制台应用程序,用于发送消息。
  5. 运行应用程序。

先决条件

创建命名空间

  1. 登录 Azure 门户

  2. 在左侧菜单中,选择“所有服务” 。 选择“集成”,搜索“中继”,将鼠标移到“中继”上方,然后选择“创建”。

    Screenshot showing the selection of Relays -> Create button.

  3. 在“创建命名空间”页上,执行以下步骤:

    1. 选择要在其中创建命名空间的 Azure 订阅。

    2. 对于资源组,选择一个要在其中放置命名空间的现有资源组,或创建一个新资源组。

    3. 输入中继命名空间的名称。

    4. 选择应托管该命名空间的区域。

    5. 在页面底部选择查看 + 创建

      Screenshot showing the Create namespace page.

    6. 在“查看 + 创建”页面上,选择“创建”。

    7. 几分钟后,将看到该命名空间的“中继”页面。

      Screenshot showing the home page for Relay namespace.

获取管理凭据

  1. 在“中继”页上,选择左侧菜单的“共享访问策略”。

  2. 在“共享访问策略”页,选择“RootManageSharedAccessKey” 。

  3. 在“SAS 策略:RootManageSharedAccessKey”下,选择“主连接字符串”旁边的“复制”按钮。 此操作会将连接字符串复制到剪贴板,供以后使用。 将此值粘贴到记事本或其他某个临时位置。

  4. 重复上述步骤,将主密钥的值复制和粘贴到临时位置,供以后使用。

    Screenshot showing the connection info for Relay namespace.

创建混合连接

在命名空间的“中继”页上,按照以下步骤创建混合连接。

  1. 请在左侧菜单中的“实体”下选择“混合连接”,然后选择“+ 混合连接”。

    Screenshot showing the Hybrid Connections page.

  2. 在“创建混合连接”页上,输入混合连接的名称,然后选择“创建”。

    Screenshot showing the Create Hybrid Connection page.

创建服务器应用程序(侦听程序)

若要侦听和接收来自中继的消息,请编写 Node.js 控制台应用程序。

创建 Node.js 应用程序

创建一个名为 listener.js 的新 JavaScript 文件。

添加中继 NPM 包

从项目文件夹中的 Node 命令提示符运行 npm install hyco-ws

编写一些代码来接收消息

  1. 将下面的常量添加到 listener.js 文件顶部。

    const WebSocket = require('hyco-ws');
    
  2. 将以下常量添加到 listener.js 文件,用于保存混合连接详细信息。 将括号中的占位符替换为在创建混合连接时获得的值。

    1. const ns - 中继命名空间。 请务必使用完全限定的命名空间名称,例如 {namespace}.servicebus.chinacloudapi.cn
    2. const path - 混合连接的名称。
    3. const keyrule - SAS 密钥的名称。
    4. const key - SAS 密钥值。
  3. 将以下代码添加到 listener.js 文件:

    var wss = WebSocket.createRelayedServer(
    {
        server : WebSocket.createRelayListenUri(ns, path),
        token: WebSocket.createRelayToken('http://' + ns, keyrule, key)
    }, 
    function (ws) {
        console.log('connection accepted');
        ws.onmessage = function (event) {
            console.log(event.data);
        };
        ws.on('close', function () {
            console.log('connection closed');
        });       
    });
    
    console.log('listening');
    
    wss.on('error', function(err) {
        console.log('error' + err);
    });
    

    listener.js 文件的内容应如下所示:

    const WebSocket = require('hyco-ws');
    
    const ns = "{RelayNamespace}";
    const path = "{HybridConnectionName}";
    const keyrule = "{SASKeyName}";
    const key = "{SASKeyValue}";
    
    var wss = WebSocket.createRelayedServer(
        {
            server : WebSocket.createRelayListenUri(ns, path),
            token: WebSocket.createRelayToken('http://' + ns, keyrule, key)
        }, 
        function (ws) {
            console.log('connection accepted');
            ws.onmessage = function (event) {
                console.log(event.data);
            };
            ws.on('close', function () {
                console.log('connection closed');
            });       
    });
    
    console.log('listening');
    
    wss.on('error', function(err) {
        console.log('error' + err);
    });
    

创建客户端应用程序(发送程序)

若要将消息发送到中继,请编写 Node.js 控制台应用程序。

创建 Node.js 应用程序

创建一个名为 sender.js 的新 JavaScript 文件。

添加中继 NPM 包

从项目文件夹中的 Node 命令提示符运行 npm install hyco-ws

编写一些代码来发送消息

  1. sender.js 文件的顶部,添加以下constants

    const WebSocket = require('hyco-ws');
    const readline = require('readline')
        .createInterface({
            input: process.stdin,
            output: process.stdout
        });;
    
  2. 将以下常量添加到 sender.js 文件,用于保存混合连接详细信息。 将括号中的占位符替换为在创建混合连接时获得的值。

    1. const ns - 中继命名空间。 请务必使用完全限定的命名空间名称,例如 {namespace}.servicebus.chinacloudapi.cn
    2. const path - 混合连接的名称。
    3. const keyrule - SAS 密钥的名称。
    4. const key - SAS 密钥值。
  3. 将以下代码添加到 sender.js 文件:

    WebSocket.relayedConnect(
        WebSocket.createRelaySendUri(ns, path),
        WebSocket.createRelayToken('http://'+ns, keyrule, key),
        function (wss) {
            readline.on('line', (input) => {
                wss.send(input, null);
            });
    
            console.log('Started client interval.');
            wss.on('close', function () {
                console.log('stopping client interval');
                process.exit();
            });
        }
    );
    

    sender.js 文件的内容应如下所示:

    const WebSocket = require('hyco-ws');
    const readline = require('readline')
        .createInterface({
            input: process.stdin,
            output: process.stdout
        });;
    
    const ns = "{RelayNamespace}";
    const path = "{HybridConnectionName}";
    const keyrule = "{SASKeyName}";
    const key = "{SASKeyValue}";
    
    WebSocket.relayedConnect(
        WebSocket.createRelaySendUri(ns, path),
        WebSocket.createRelayToken('http://'+ns, keyrule, key),
        function (wss) {
            readline.on('line', (input) => {
                wss.send(input, null);
            });
    
            console.log('Started client interval.');
            wss.on('close', function () {
                console.log('stopping client interval');
                process.exit();
            });
        }
    );
    

运行应用程序

  1. 运行服务器应用程序:在 Node.js 命令提示符处,键入 node listener.js

  2. 运行客户端应用程序:在 Node.js 命令提示符处键入 node sender.js,然后输入某些文本。

  3. 确保服务器应用程序控制台输出了客户端应用程序中输入的文本。

    Console windows testing both the server and client applications.

祝贺你,现已使用 Node.js 创建端到端混合连接应用程序!

后续步骤

在本快速入门中,你创建了 Node.js 客户端和服务器应用程序,此类程序使用 WebSocket 来发送和接收消息。 Azure 中继的混合连接功能也支持使用 HTTP 发送和接收消息。 若要了解如何将 HTTP 与 Azure 中继混合连接配合使用,请参阅 Node.js HTTP 快速入门

在本快速入门中,你使用了 Node.js 来创建客户端和服务器应用程序。 若要了解如何使用 .NET Framework 编写客户端和服务器应用程序,请参阅 .NET WebSocket 快速入门.NET HTTP 快速入门