中继混合连接 Node API 概述Relay Hybrid Connections Node API overview

概述Overview

Azure 中继混合连接的 hyco-ws 节点包是在 ‘ws’ NPM 包的基础上进行构建和扩展的。The hyco-ws Node package for Azure Relay Hybrid Connections is built on and extends the 'ws' NPM package. 此包将重新导出该基程序包的所有导出,并添加允许与 Azure 中继服务混合连接功能集成的新导出。This package re-exports all exports of that base package and adds new exports that enable integration with the Azure Relay service Hybrid Connections feature.

在现有应用程序中,require('ws') 可以改为结合使用此包与 require('hyco-ws'),从而还可以实现混合方案,其中应用程序可以同时从“防火墙内”和通过混合连接本地侦听 WebSocket 连接。Existing applications that require('ws') can use this package with require('hyco-ws') instead, which also enables hybrid scenarios in which an application can listen for WebSocket connections locally from "inside the firewall" and via Hybrid Connections, all at the same time.

文档Documentation

API 记录于主要的 ‘ws’ 包中The APIs are documented in the main 'ws' package. 本文介绍此包与该基线有何不同。This article describes how this package differs from that baseline.

基程序包和此 ‘hyco-ws’ 之间的主要区别是添加了新的服务器类、通过 require('hyco-ws').RelayedServer 导出以及添加了一些帮助程序方法。The key differences between the base package and this 'hyco-ws' is that it adds a new server class, exported via require('hyco-ws').RelayedServer, and a few helper methods.

包帮助程序方法Package helper methods

包导出上提供了几种实用方法,可按以下方式引用:There are several utility methods available on the package export that you can reference as follows:

const WebSocket = require('hyco-ws');

var listenUri = WebSocket.createRelayListenUri('namespace.servicebus.windows.net', 'path');
listenUri = WebSocket.appendRelayToken(listenUri, 'ruleName', '...key...')
...

帮助程序方法可用于此包,但也可用于节点服务器,使 Web 或设备客户端能够创建侦听器或发件人。The helper methods are for use with this package, but can also be used by a Node server for enabling web or device clients to create listeners or senders. 服务器使用这些方法时,向它们传递嵌入生存期较短的令牌的 URI。The server uses these methods by passing them URIs that embed short-lived tokens. 这些 URI 也可用于不支持设置 WebSocket 握手的 HTTP 头的常见 WebSocket 堆栈。These URIs can also be used with common WebSocket stacks that do not support setting HTTP headers for the WebSocket handshake. 将授权令牌嵌入到 URI 主要针对这些库外使用方案。Embedding authorization tokens into the URI is supported primarily for those library-external usage scenarios.

createRelayListenUricreateRelayListenUri

var uri = createRelayListenUri([namespaceName], [path], [[token]], [[id]])

为给定命名空间和路径创建有效的 Azure 中继混合连接侦听器 URI。Creates a valid Azure Relay Hybrid Connection listener URI for the given namespace and path. 此 URI 随后可用于 WebSocketServer 类的中继版本。This URI can then be used with the relay version of the WebSocketServer class.

  • namespaceName(必需)- 要使用的 Azure 中继命名空间的域限定名称。namespaceName (required) - the domain-qualified name of the Azure Relay namespace to use.
  • path(必需)- 该命名空间中现有 Azure 中继混合连接的名称。path (required) - the name of an existing Azure Relay Hybrid Connection in that namespace.
  • token(可选)- 以前颁发的中继访问令牌,嵌入到侦听器 URI 中(请参阅以下示例)。token (optional) - a previously issued Relay access token that is embedded in the listener URI (see the following example).
  • id(可选)- 用于启用请求的端到端诊断跟踪的跟踪标识符。id (optional) - a tracking identifier that enables end-to-end diagnostics tracking of requests.

token 值是可选的,仅在不可能发送 HTTP 头和 WebSocket 握手时使用,这与 W3C WebSocket 堆栈的情况相同。The token value is optional and should only be used when it is not possible to send HTTP headers along with the WebSocket handshake, as is the case with the W3C WebSocket stack.

createRelaySendUricreateRelaySendUri

var uri = createRelaySendUri([namespaceName], [path], [[token]], [[id]])

为给定命名空间和路径创建有效的 Azure 中继混合连接发送 URI。Creates a valid Azure Relay Hybrid Connection send URI for the given namespace and path. 此 URI 可与任何 WebSocket 客户端配合使用。This URI can be used with any WebSocket client.

  • namespaceName(必需)- 要使用的 Azure 中继命名空间的域限定名称。namespaceName (required) - the domain-qualified name of the Azure Relay namespace to use.
  • path(必需)- 该命名空间中现有 Azure 中继混合连接的名称。path (required) - the name of an existing Azure Relay Hybrid Connection in that namespace.
  • token(可选)- 以前颁发的中继访问令牌,嵌入到发送 URI 中(请参阅以下示例)。token (optional) - a previously issued Relay access token that is embedded in the send URI (see the following example).
  • id(可选)- 用于启用请求的端到端诊断跟踪的跟踪标识符。id (optional) - a tracking identifier that enables end-to-end diagnostics tracking of requests.

token 值是可选的,仅在不可能发送 HTTP 头和 WebSocket 握手时使用,这与 W3C WebSocket 堆栈的情况相同。The token value is optional and should only be used when it is not possible to send HTTP headers along with the WebSocket handshake, as is the case with the W3C WebSocket stack.

createRelayTokencreateRelayToken

var token = createRelayToken([uri], [ruleName], [key], [[expirationSeconds]])

为给定目标 URI、SAS 规则和 SAS 规则密钥创建 Azure 中继共享访问签名 (SAS) 令牌,其有效期为指定的数秒钟或者如果忽略到期参数,则为从当前时刻起一小时。Creates an Azure Relay Shared Access Signature (SAS) token for the given target URI, SAS rule, and SAS rule key that is valid for the given number of seconds or for an hour from the current instant if the expiry argument is omitted.

  • uri(必需)- 为之颁发令牌的 URI。uri (required) - the URI for which the token is to be issued. 规范化此 URI 以使用 HTTP 方案,且将除去查询字符串信息。The URI is normalized to use the HTTP scheme, and query string information is stripped.
  • ruleName(必需)- 由给定 URI 表示的实体的 SAS 规则名称,或者由 URI 主机部分表示的命名空间的 SAS 规则名称。ruleName (required) - SAS rule name for either the entity represented by the given URI, or for the namespace represented by the URI host portion.
  • key(必需)- SAS 规则的有效密钥。key (required) - valid key for the SAS rule.
  • expirationSeconds(可选)- 已生成的令牌过期之前的秒数。expirationSeconds (optional) - the number of seconds until the generated token should expire. 如果未指定,则默认值为 1 小时 (3600)。If not specified, the default is 1 hour (3600).

颁发的令牌在给定的时间段内授予指定的 SAS 规则相关的权限。The issued token confers the rights associated with the specified SAS rule for the given duration.

appendRelayTokenappendRelayToken

var uri = appendRelayToken([uri], [ruleName], [key], [[expirationSeconds]])

此方法在功能上等效于之前记录的 createRelayToken 方法,但返回正确追加到输入 URI 的令牌。This method is functionally equivalent to the createRelayToken method documented previously, but returns the token correctly appended to the input URI.

Class ws.RelayedServerClass ws.RelayedServer

hycows.RelayedServer 类可替代 ws.Server 类,不侦听本地网络,但委托侦听 Azure 中继服务。The hycows.RelayedServer class is an alternative to the ws.Server class that does not listen on the local network, but delegates listening to the Azure Relay service.

这两个类通常为约定兼容,也就是说,使用 ws.Server 类的现有应用程序可以轻易改为使用中继版本。The two classes are mostly contract compatible, meaning that an existing application using the ws.Server class can easily be changed to use the relayed version. 主要差异在于构造函数和可用选项。The main differences are in the constructor and in the available options.

构造函数Constructor

var ws = require('hyco-ws');
var server = ws.RelayedServer;

var wss = new server(
    {
        server: ws.createRelayListenUri(ns, path),
        token: function() { return ws.createRelayToken('http://' + ns, keyrule, key); }
    });

RelayedServer 构造函数支持一组不同的参数,而不支持 Server,因为该函数既不是独立侦听器,也不能嵌入到现有 HTTP 侦听器框架中。The RelayedServer constructor supports a different set of arguments than the Server, because it is not a standalone listener, or able to be embedded into an existing HTTP listener framework. 自从将 WebSocket 管理大幅委托到中继服务后,也有少数选项可用。There are also fewer options available since the WebSocket management is largely delegated to the Relay service.

构造函数参数:Constructor arguments:

  • server(必需)- 要侦听的混合连接名称的完全限定 URI,通常使用 WebSocket.createRelayListenUri() 帮助程序方法构造。server (required) - the fully qualified URI for a Hybrid Connection name on which to listen, usually constructed with the WebSocket.createRelayListenUri() helper method.
  • token(必需)- 此参数可以保留以前颁发的令牌字符串,也可以保留为获得此类令牌字符串而调用的回调函数。token (required) - this argument holds either a previously issued token string or a callback function that can be called to obtain such a token string. 在启用令牌续订时,首选回调选项。The callback option is preferred, as it enables token renewal.

事件Events

RelayedServer 实例将发出三个事件,使你能够处理传入的请求、建立连接,以及检测错误条件。RelayedServer instances emit three events that enable you to handle incoming requests, establish connections, and detect error conditions. 订阅 connect 事件后才能处理消息。You must subscribe to the connect event to handle messages.

headersheaders
function(headers)

接受传入连接前将引发 headers 事件,可以实现将标头的修改发送到客户端。The headers event is raised just before an incoming connection is accepted, enabling modification of the headers to send to the client.

连接connection
function(socket)

接受新的 WebSocket 连接时发出。Emitted when a new WebSocket connection is accepted. 此对象的类型为 ws.WebSocket,与基程序包相同。The object is of type ws.WebSocket, same as with the base package.

errorerror
function(error)

如果基础服务器发出错误,则会转发到此处。If the underlying server emits an error, it is forwarded here.

帮助程序Helpers

为了简化中继服务器的启动和对传入连接的即时订阅,该包公开了一个简单的帮助程序函数,该函数也用于本示例中,如下所示:To simplify starting a relayed server and immediately subscribing to incoming connections, the package exposes a simple helper function, which is also used in the examples, as follows:

createRelayedListenercreateRelayedListener
var WebSocket = require('hyco-ws');

var wss = WebSocket.createRelayedServer(
    {
        server: WebSocket.createRelayListenUri(ns, path),
        token: function() { return WebSocket.createRelayToken('http://' + ns, keyrule, key); }
    }, 
    function (ws) {
        console.log('connection accepted');
        ws.onmessage = function (event) {
            console.log(JSON.parse(event.data));
        };
        ws.on('close', function () {
            console.log('connection closed');
        });       
});
createRelayedServercreateRelayedServer
var server = createRelayedServer([options], [connectCallback] )

此方法调用构造函数以创建 RelayedServer 的新实例,并订阅提供的 'connection' 事件的回调。This method calls the constructor to create a new instance of the RelayedServer and then subscribes the provided callback to the 'connection' event.

relayedConnectrelayedConnect

只需在函数中生成 createRelayedServer 帮助程序的镜像,relayedConnect 会创建客户端连接,并订阅生成套接字上的 'open' 事件。Simply mirroring the createRelayedServer helper in function, relayedConnect creates a client connection and subscribes to the 'open' event on the resulting socket.

var uri = WebSocket.createRelaySendUri(ns, path);
WebSocket.relayedConnect(
    uri,
    WebSocket.createRelayToken(uri, keyrule, key),
    function (socket) {
        ...
    }
);

后续步骤Next steps

若要了解有关 Azure 中继的详细信息,请访问以下链接:To learn more about Azure Relay, visit these links: