开始在 Node.js 中使用中继混合连接 WebSocketGet started with Relay Hybrid Connections WebSockets in Node.js

在本快速入门中,请创建 Node.js 发送者和接收者应用程序,以便在 Azure 中继中通过混合连接 WebSocket 发送和接收消息。In this quickstart, you create Node.js sender and receiver applications that send and receive messages by using Hybrid Connections WebSockets in Azure Relay. 若要了解 Azure 中继的常规信息,请参阅 Azure 中继To learn about Azure Relay in general, see Azure Relay.

在本快速入门中,你将执行以下步骤:In this quickstart, you take the following steps:

  1. 使用 Azure 门户创建中继命名空间。Create a Relay namespace by using the Azure portal.
  2. 使用 Azure 门户在该命名空间中创建混合连接。Create a hybrid connection in that namespace by using the Azure portal.
  3. 编写服务器(侦听器)控制台应用程序,用于接收消息。Write a server (listener) console application to receive messages.
  4. 编写客户端(发送方)控制台应用程序,用于发送消息。Write a client (sender) console application to send messages.
  5. 运行应用程序。Run applications.

必备条件Prerequisites

创建命名空间Create a namespace

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 选择“创建资源”。Select Create a resource. 然后,选择“集成” > “中继”。Then, select Integration > Relay. 如果未在列表中看到“中继”,请选择右上角的“查看全部”。If you don't see Relay in the list, select See All in the top-right corner.

  3. 选择“创建”,然后在“名称”字段中输入命名空间名称。Select Create, and enter a namespace name in the Name field. Azure 门户会检查该名称是否可用。Azure portal checks to see if the name is available.

  4. 选择要在其中创建命名空间的 Azure 订阅。Choose an Azure subscription in which to create the namespace.

  5. 对于资源组,选择一个要在其中放置命名空间的现有资源组,或创建一个新资源组。For Resource group, choose an existing resource group in which to place the namespace, or create a new one.

  6. 选择应托管该命名空间的国家或地区。Select the country or region in which your namespace should be hosted.

    创建命名空间

  7. 选择“创建” 。Select Create. 系统会创建并启用命名空间。The system creates your namespace and enables it. 几分钟后,系统为用户的帐户预配资源。After a few minutes, the system provisions resources for your account.

获取管理凭据Get management credentials

  1. 选择“所有资源”,然后选择新建的命名空间名称。Select All resources, and then choose the newly created namespace name.

  2. 选择“共享访问策略”。Select Shared access policies.

  3. 在“共享访问策略”下,选择“RootManageSharedAccessKey”。Under Shared access policies, select RootManageSharedAccessKey.

  4. 在“SAS 策略:RootManageSharedAccessKey”下,选择“主连接字符串”旁边的“复制”按钮。Under SAS Policy: RootManageSharedAccessKey, select the Copy button next to Primary Connection String. 此操作会将连接字符串复制到剪贴板,供以后使用。This action copies the connection string to your clipboard for later use. 将此值粘贴到记事本或其他某个临时位置。Paste this value into Notepad or some other temporary location.

  5. 重复上述步骤,将主密钥的值复制和粘贴到临时位置,供以后使用。Repeat the preceding step to copy and paste the value of Primary key to a temporary location for later use.

    连接字符串

创建混合连接Create a hybrid connection

确保已创建中继命名空间Ensure that you have already created a Relay namespace.

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 在左侧菜单中,选择“所有资源”。In the left menu, select All resources.

  3. 选择要在其中创建混合连接的命名空间。Select the namespace where you want to create the hybrid connection. 在本示例中,该命名空间为 mynewnsIn this case, it is mynewns.

  4. 在“中继命名空间”下选择“混合连接”。Under Relay namespace, select Hybrid Connections.

    创建混合连接

  5. 在命名空间概览窗口中,选择“+ 混合连接”In the namespace overview window, select + Hybrid Connection

    选择混合连接

  6. 在“创建混合连接”下输入一个值,作为混合连接名称。Under Create Hybrid Connection, enter a value for the hybrid connection name. 保留其他默认值。Leave the other default values.

    选择“新建”

  7. 选择“创建” 。Select Create.

创建服务器应用程序(侦听程序)Create a server application (listener)

若要侦听和接收来自中继的消息,请编写 Node.js 控制台应用程序。To listen and receive messages from the Relay, write a Node.js console application.

创建 Node.js 应用程序Create a Node.js application

创建一个名为 listener.js 的新 JavaScript 文件。Create a new JavaScript file called listener.js.

添加中继 NPM 包Add the Relay NPM package

从项目文件夹中的 Node 命令提示符运行 npm install hyco-wsRun npm install hyco-ws from a Node command prompt in your project folder.

编写一些代码来接收消息Write some code to receive messages

  1. 将下面的常量添加到 listener.js 文件顶部。Add the following constant to the top of the listener.js file.

    const WebSocket = require('hyco-ws');
    
  2. 将以下常量添加到 listener.js 文件,用于保存混合连接详细信息。Add the following constants to the listener.js file for the hybrid connection details. 将括号中的占位符替换为在创建混合连接时获得的值。Replace the placeholders in brackets with the values you obtained when you created the hybrid connection.

    1. const ns - 中继命名空间。const ns - The Relay namespace. 请务必使用完全限定的命名空间名称,例如 {namespace}.servicebus.chinacloudapi.cnBe sure to use the fully qualified namespace name; for example, {namespace}.servicebus.chinacloudapi.cn.
    2. const path - 混合连接的名称。const path - The name of the hybrid connection.
    3. const keyrule - SAS 密钥的名称。const keyrule - The name of the SAS key.
    4. const key - SAS 密钥值。const key - The SAS key value.
  3. 将以下代码添加到 listener.js 文件:Add the following code to the listener.js file:

    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 文件的内容应如下所示:Here is what your listener.js file should look like:

    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);
    });
    

创建客户端应用程序(发送程序)Create a client application (sender)

若要将消息发送到中继,请编写 Node.js 控制台应用程序。To send messages to the Relay, write a Node.js console application.

创建 Node.js 应用程序Create a Node.js application

创建一个名为 sender.js 的新 JavaScript 文件。Create a new JavaScript file called sender.js.

添加中继 NPM 包Add the Relay NPM package

从项目文件夹中的 Node 命令提示符运行 npm install hyco-wsRun npm install hyco-ws from a Node command prompt in your project folder.

编写一些代码来发送消息Write some code to send messages

  1. sender.js 文件的顶部,添加以下constantsAdd the following constants to the top of the sender.js file.

    const WebSocket = require('hyco-ws');
    const readline = require('readline')
        .createInterface({
            input: process.stdin,
            output: process.stdout
        });;
    
  2. 将以下常量添加到 sender.js 文件,用于保存混合连接详细信息。Add the following constants to the sender.js file for the hybrid connection details. 将括号中的占位符替换为在创建混合连接时获得的值。Replace the placeholders in brackets with the values you obtained when you created the hybrid connection.

    1. const ns - 中继命名空间。const ns - The Relay namespace. 请务必使用完全限定的命名空间名称,例如 {namespace}.servicebus.windows.netBe sure to use the fully qualified namespace name; for example, {namespace}.servicebus.windows.net.
    2. const path - 混合连接的名称。const path - The name of the hybrid connection.
    3. const keyrule - SAS 密钥的名称。const keyrule - The name of the SAS key.
    4. const key - SAS 密钥值。const key - The SAS key value.
  3. 将以下代码添加到 sender.js 文件:Add the following code to the sender.js file:

    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 文件的内容应如下所示:Here is what your sender.js file should look like:

    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();
            });
        }
    );
    

运行应用程序Run the applications

  1. 运行服务器应用程序:在 Node.js 命令提示符处,键入 node listener.jsRun the server application: from a Node.js command prompt type node listener.js.

  2. 运行客户端应用程序:在 Node.js 命令提示符处键入 node sender.js,然后输入某些文本。Run the client application: from a Node.js command prompt type node sender.js, and enter some text.

  3. 确保服务器应用程序控制台输出了客户端应用程序中输入的文本。Ensure that the server application console outputs the text that was entered in the client application.

    running-applications

祝贺你,现已使用 Node.js 创建端到端混合连接应用程序!Congratulations, you have created an end-to-end Hybrid Connections application using Node.js!

后续步骤Next steps

在本快速入门中,你创建了 Node.js 客户端和服务器应用程序,此类程序使用 WebSocket 来发送和接收消息。In this quickstart, you created Node.js client and server applications that used WebSockets to send and receive messages. Azure 中继的混合连接功能也支持使用 HTTP 发送和接收消息。The Hybrid Connections feature of Azure Relay also supports using HTTP to send and receive messages. 若要了解如何将 HTTP 与 Azure 中继混合连接配合使用,请参阅 Node.js HTTP 快速入门To learn how to use HTTP with Azure Relay Hybrid Connections, see the Node.js HTTP quickstart.

在本快速入门中,你使用了 Node.js 来创建客户端和服务器应用程序。In this quickstart, you used Node.js to create client and server applications. 若要了解如何使用 .NET Framework 编写客户端和服务器应用程序,请参阅 .NET WebSocket 快速入门.NET HTTP 快速入门To learn how to write client and server applications using .NET Framework, see the .NET WebSockets quickstart or the .NET HTTP quickstart.