开始在 Node 中使用中继混合连接 HTTP 请求Get started with Relay Hybrid Connections HTTP requests in Node

在本快速入门中,请创建 Node.js 发送者和接收者应用程序,用于通过 HTTP 协议发送和接收消息。In this quickstart, you create Node.js sender and receiver applications that send and receive messages by using the HTTP protocol. 这些应用程序使用 Azure 中继的混合连接功能。The applications use Hybrid Connections feature of 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

1.使用 Azure 门户创建命名空间1. Create a namespace using the Azure portal

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

  2. 在左侧菜单中,选择“+ 创建资源”。In the left menu, select + Create a resource. 然后,选择“企业集成” > “中继”。Then, select Enterprise Integration > Relay.

  3. 在“创建命名空间”下输入命名空间名称。Under Create namespace, enter a namespace name. 系统会立即检查该名称是否可用。The system immediately checks to see if the name is available.

  4. 在“订阅”框中,选择要在其中创建命名空间的 Azure 订阅。In the Subscription box, select an Azure subscription in which to create the namespace.

  5. “资源组”框中,选择要在其中放置命名空间的现有资源组,或者创建新资源组。In the Resource group box, select an existing resource group in which to place the namespace, or create a new one.

  6. 在“位置”中,选择应托管命名空间的国家或地区。In Location, 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 select the newly created namespace name.

  2. 在“中继命名空间”下,选择“共享访问策略”。Under the Relay namespace, select Shared access policies.

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

    connection-info

  4. 在“策略: RootManageSharedAccessKey”下选择“连接字符串 - 主密钥”旁边的“复制”按钮。Under Policy: RootManageSharedAccessKey, select the Copy button next to Connection string–Primary key. 这样会将连接字符串复制到剪贴板,供以后使用。This 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.

2.使用 Azure 门户创建混合连接2. Create a hybrid connection using the Azure portal

确保已创建中继命名空间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.

3.创建服务器应用程序(侦听程序)3. 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-httpsRun npm install hyco-https from a Node command prompt in your project folder.

编写一些代码以处理请求Write some code to handle requests

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

    const https = require('hyco-https');
    
  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.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. 将以下代码添加到 listener.js 文件。Add the following code to the listener.js file. ::

    可以发现,该代码与 Node.js 入门教程中提供的任何简单 HTTP 服务器示例并无太大不同,只是使用的是 createRelayedServer 而不是典型的 createServer 函数。You will notice that the code is not much different from any simple HTTP server example you can find in Node.js beginner tutorials, which the exception of using the createRelayedServer instead of the typical createServer function.

    var uri = https.createRelayListenUri(ns, path);
    var server = https.createRelayedServer(
        {
            server : uri,
            token : () => https.createRelayToken(uri, keyrule, key)
        },
        (req, res) => {
            console.log('request accepted: ' + req.method + ' on ' + req.url);
            res.setHeader('Content-Type', 'text/html');
            res.end('<html><head><title>Hey!</title></head><body>Relayed Node.js Server!</body></html>');
        });
    
    server.listen( (err) => {
            if (err) {
              return console.log('something bad happened', err)
            }
            console.log(`server is listening on ${port}`)
          });
    
    server.on('error', (err) => {
        console.log('error: ' + err);
    });
    

    listener.js 文件的内容应如下所示:Here is what your listener.js file should look like:

    const https = require('hyco-https');
    
    const ns = "{RelayNamespace}";
    const path = "{HybridConnectionName}";
    const keyrule = "{SASKeyName}";
    const key = "{SASKeyValue}";
    
    var uri = https.createRelayListenUri(ns, path);
    var server = https.createRelayedServer(
        {
            server : uri,
            token : () => https.createRelayToken(uri, keyrule, key)
        },
        (req, res) => {
            console.log('request accepted: ' + req.method + ' on ' + req.url);
            res.setHeader('Content-Type', 'text/html');
            res.end('<html><head><title>Hey!</title></head><body>Relayed Node.js Server!</body></html>');
        });
    
    server.listen( (err) => {
            if (err) {
              return console.log('something bad happened', err)
            }
            console.log(`server is listening on ${port}`)
          });
    
    server.on('error', (err) => {
        console.log('error: ' + err);
    });
    

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

若要将消息发送到中继,可使用任何 HTTP 客户端,或编写 Node.js 控制台应用程序。To send messages to the Relay, you can use any HTTP client, or write a Node.js console application.

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

如果创建中继时已禁用“需要客户端授权”选项,可使用任何浏览器向混合连接 URL 发送请求。If you have disabled the "Requires Client Authorization" option when creating the Relay, you can send requests to the Hybrid Connections URL with any browser. 若要访问受保护的终结点,需在 ServiceBusAuthorization 标头中创建并传递令牌,如下所示。For accessing protected endpoints, you need to create and pass a token in the ServiceBusAuthorization header, which is shown here.

首先,创建一个名为 sender.js 的新 JavaScript 文件。To start, create a new JavaScript file called sender.js.

添加中继 NPM 包Add the Relay NPM package

从项目文件夹中的 Node 命令提示符运行 npm install hyco-httpsRun npm install hyco-https from a Node command prompt in your project folder. 此包还会导入常规 https 包。This package also imports the regular https package. 对于客户端,主要的区别在于该包会提供用于构造中继 URI 和令牌的函数。For the client-side, the key difference is that the package provides functions to construct Relay URIs and tokens.

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

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

    const https = require('hyco-https');
    
  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. 可以发现,该代码与 Node.js HTTPS 客户端的常规用法并无太大不同,只是前者添加了授权标头。You will notice that the code does not differ significantly from the regular use of the Node.js HTTPS client; it just adds the authorization header.

    https.get({
        hostname : ns,
        path : (!path || path.length == 0 || path[0] !== '/'?'/':'') + path,
        port : 443,
        headers : {
            'ServiceBusAuthorization' : 
                https.createRelayToken(https.createRelayHttpsUri(ns, path), keyrule, key)
        }
    }, (res) => {
        let error;
        if (res.statusCode !== 200) {
            console.error('Request Failed.\n Status Code: ${statusCode}');
            res.resume();
        } 
        else {
            res.setEncoding('utf8');
            res.on('data', (chunk) => {
                console.log(`BODY: ${chunk}`);
            });
            res.on('end', () => {
                console.log('No more data in response.');
            });
        };
    }).on('error', (e) => {
        console.error(`Got error: ${e.message}`);
    });
    

    sender.js 文件的内容应如下所示:Here is what your sender.js file should look like:

    const https = require('hyco-https');
    
    const ns = "{RelayNamespace}";
    const path = "{HybridConnectionName}";
    const keyrule = "{SASKeyName}";
    const key = "{SASKeyValue}";
    
    https.get({
        hostname : ns,
        path : (!path || path.length == 0 || path[0] !== '/'?'/':'') + path,
        port : 443,
        headers : {
            'ServiceBusAuthorization' : 
                https.createRelayToken(https.createRelayHttpsUri(ns, path), keyrule, key)
        }
    }, (res) => {
        let error;
        if (res.statusCode !== 200) {
            console.error('Request Failed.\n Status Code: ${statusCode}');
            res.resume();
        } 
        else {
            res.setEncoding('utf8');
            res.on('data', (chunk) => {
                console.log(`BODY: ${chunk}`);
            });
            res.on('end', () => {
                console.log('No more data in response.');
            });
        };
    }).on('error', (e) => {
        console.error(`Got error: ${e.message}`);
    });
    

5.运行应用程序5. 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.

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

后续步骤Next steps

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