Sdílet prostřednictvím


Začínáme s objekty WebSocket Relay Hybrid Connections v .NET

V tomto rychlém startu vytvoříte aplikace odesílatele a příjemce .NET, které odesílají a přijímají zprávy pomocí webSocketů hybridních připojení v Azure Relay. Obecné informace o Azure Relay najdete v tématu Azure Relay.

V tomto rychlém startu provedete následující kroky:

  1. Pomocí webu Azure Portal vytvoříte obor názvů služby Relay.
  2. Pomocí webu Azure Portal vytvoříte v tomto oboru názvů hybridní připojení.
  3. Napíšeme konzolovou aplikaci serveru (naslouchacího procesu) pro příjem zpráv.
  4. Napíšeme konzolovou aplikaci klienta (odesílatele) pro odesílání zpráv.
  5. Spusťte aplikace.

Požadavky

Pro absolvování tohoto kurzu musí být splněné následující požadavky:

Vytvoření oboru názvů

  1. Přihlaste se k portálu Azure.

  2. V nabídce vlevo vyberte Všechny služby . Vyberte Možnost Integrace, vyhledejte Relays, přesuňte myš na Relays a pak vyberte Vytvořit.

    Snímek obrazovky s výběrem tlačítka Relays –> Vytvořit

  3. Na stránce Vytvořit obor názvů postupujte takto:

    1. Zvolte předplatné Azure, ve kterém chcete vytvořit obor názvů.

    2. Pro skupinu prostředků zvolte existující skupinu prostředků, do které chcete obor názvů umístit, nebo vytvořte novou.

    3. Zadejte název oboru názvů služby Relay.

    4. Vyberte oblast, ve které má být váš obor názvů hostovaný.

    5. Vyberte Zkontrolovat a vytvořit v dolní části stránky.

      Snímek obrazovky se stránkou Vytvořit obor názvů

    6. Na stránce Zkontrolovat a vytvořit vyberte Vytvořit.

    7. Po několika minutách se zobrazí stránka Relay pro obor názvů.

      Snímek obrazovky s domovskou stránkou oboru názvů služby Relay

Získání přihlašovacích údajů pro správu

  1. Na stránce Relay vyberte v nabídce vlevo zásady sdíleného přístupu. `

  2. Na stránce Zásady sdíleného přístupu vyberte RootManageSharedAccessKey.

  3. V části Zásady SAS: RootManageSharedAccessKey vyberte tlačítko Kopírovat vedle primárního připojovacího řetězce. Tato akce zkopíruje připojovací řetězec do schránky pro pozdější použití. Vložte tuto hodnotu do Poznámkového bloku nebo jiného dočasného umístění.

  4. Zopakujte předchozí krok, zkopírujte si hodnotu primárního klíče a vložte ji do dočasného umístění pro pozdější použití.

    Snímek obrazovky zobrazující informace o připojení pro obor názvů služby Relay

Přidání hybridního připojení

Na stránce Relay pro váš obor názvů vytvořte hybridní připojení pomocí následujícího postupu.

  1. V nabídce vlevo v části Entity vyberte Hybridní připojení a pak vyberte + Hybridní připojení.

    Snímek obrazovky se stránkou Hybridní připojení

  2. Na stránce Vytvořit hybridní připojení zadejte název hybridního připojení a vyberte Vytvořit.

    Snímek obrazovky se stránkou Vytvořit hybridní připojení

Vytvoření serverové aplikace (naslouchací proces)

Napište v sadě Visual Studio konzolovou aplikaci v jazyce C#, která bude naslouchat a přijímat zprávy z předávací služby.

Vytvoření konzolové aplikace

V sadě Visual Studio vytvořte nový projekt Konzolová aplikace (.NET Framework).

Přidání balíčku NuGet služby Relay

  1. Klikněte pravým tlačítkem na nově vytvořený projekt a vyberte možnost Spravovat balíčky NuGet.
  2. Vyberte Procházet a vyhledejte Microsoft.Azure.Relay. Ve výsledcích hledání vyberte Microsoft Azure Relay.
  3. Vyberte Nainstalovat a dokončete instalaci. Zavřete dialogové okno.

Napsání kódu pro přijímání zpráv

  1. Na začátku souboru Program.cs nahraďte existující příkazy using následujícími příkazy using:

    using System;
    using System.IO;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Net;
    using Microsoft.Azure.Relay;
    
  2. Do třídy Program přidejte konstanty s podrobnostmi o hybridním připojení. Zástupné symboly nahraďte hodnotami, které jste získali při vytváření hybridního připojení. Nezapomeňte použít plně kvalifikovaný obor názvů.

    // replace {RelayNamespace} with the name of your namespace
    private const string RelayNamespace = "YOUR-RELAY-NAMESPACE-NAME.servicebus.windows.net";
    
    // replace {HybridConnectionName} with the name of your hybrid connection
    private const string ConnectionName = "HYBRID-CONNECTION-NAME";
    
    // replace {SAKKeyName} with the name of your Shared Access Policies key, which is RootManageSharedAccessKey by default
    private const string KeyName = "SAS-KEY-NAME";
    
    // replace {SASKey} with the primary key of the namespace you saved earlier
    private const string Key = "SAS-KEY-VALUE";
    
  3. Do třídy Program přidejte metodu ProcessMessagesOnConnection:

    // The method initiates the connection.
    private static async void ProcessMessagesOnConnection(HybridConnectionStream relayConnection, CancellationTokenSource cts)
    {
        Console.WriteLine("New session");
    
        // The connection is a fully bidrectional stream. 
        // Put a stream reader and a stream writer over it.  
        // This allows you to read UTF-8 text that comes from 
        // the sender, and to write text replies back.
        var reader = new StreamReader(relayConnection);
        var writer = new StreamWriter(relayConnection) { AutoFlush = true };
        while (!cts.IsCancellationRequested)
        {
            try
            {
                // Read a line of input until a newline is encountered.
                var line = await reader.ReadLineAsync();
    
                if (string.IsNullOrEmpty(line))
                {
                    // If there's no input data, signal that 
                    // you will no longer send data on this connection,
                    // and then break out of the processing loop.
                    await relayConnection.ShutdownAsync(cts.Token);
                    break;
                }
    
                // Write the line on the console.
                Console.WriteLine(line);
    
                // Write the line back to the client, prepended with "Echo:"
                await writer.WriteLineAsync($"Echo: {line}");
            }
            catch (IOException)
            {
                // Catch an I/O exception. This likely occurred when
                // the client disconnected.
                Console.WriteLine("Client closed connection");
                break;
            }
        }
    
        Console.WriteLine("End session");
    
        // Close the connection.
        await relayConnection.CloseAsync(cts.Token);
    }
    
  4. Do třídy Program přidejte metodu RunAsync:

    private static async Task RunAsync()
    {
        var cts = new CancellationTokenSource();
    
        var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
        var listener = new HybridConnectionListener(new Uri(string.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);
    
        // Subscribe to the status events.
        listener.Connecting += (o, e) => { Console.WriteLine("Connecting"); };
        listener.Offline += (o, e) => { Console.WriteLine("Offline"); };
        listener.Online += (o, e) => { Console.WriteLine("Online"); };
    
        // Opening the listener establishes the control channel to
        // the Azure Relay service. The control channel is continuously 
        // maintained, and is reestablished when connectivity is disrupted.
        await listener.OpenAsync(cts.Token);
        Console.WriteLine("Server listening");
    
        // Provide callback for the cancellation token that will close the listener.
        cts.Token.Register(() => listener.CloseAsync(CancellationToken.None));
    
        // Start a new thread that will continuously read the console.
        new Task(() => Console.In.ReadLineAsync().ContinueWith((s) => { cts.Cancel(); })).Start();
    
        // Accept the next available, pending connection request. 
        // Shutting down the listener allows a clean exit. 
        // This method returns null.
        while (true)
        {
            var relayConnection = await listener.AcceptConnectionAsync();
            if (relayConnection == null)
            {
                break;
            }
    
            ProcessMessagesOnConnection(relayConnection, cts);
        }
    
        // Close the listener after you exit the processing loop.
        await listener.CloseAsync(cts.Token);
    }
    
  5. Do metody Main ve třídě Program přidejte následující řádek kódu:

    RunAsync().GetAwaiter().GetResult();
    

    Hotový soubor Program.cs by měl vypadat nějak takto:

    namespace Server
    {
        using System;
        using System.IO;
        using System.Threading;
        using System.Threading.Tasks;
        using Microsoft.Azure.Relay;
    
        public class Program
        {
            private const string RelayNamespace = "{RelayNamespace}.servicebus.windows.net";
            private const string ConnectionName = "{HybridConnectionName}";
            private const string KeyName = "{SASKeyName}";
            private const string Key = "{SASKey}";
    
            public static void Main(string[] args)
            {
                RunAsync().GetAwaiter().GetResult();
            }
    
            private static async Task RunAsync()
            {
                var cts = new CancellationTokenSource();
    
                var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
                var listener = new HybridConnectionListener(new Uri(string.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);
    
                // Subscribe to the status events.
                listener.Connecting += (o, e) => { Console.WriteLine("Connecting"); };
                listener.Offline += (o, e) => { Console.WriteLine("Offline"); };
                listener.Online += (o, e) => { Console.WriteLine("Online"); };
    
                // Opening the listener establishes the control channel to
                // the Azure Relay service. The control channel is continuously 
                // maintained, and is reestablished when connectivity is disrupted.
                await listener.OpenAsync(cts.Token);
                Console.WriteLine("Server listening");
    
                // Provide callback for a cancellation token that will close the listener.
                cts.Token.Register(() => listener.CloseAsync(CancellationToken.None));
    
                // Start a new thread that will continuously read the console.
                new Task(() => Console.In.ReadLineAsync().ContinueWith((s) => { cts.Cancel(); })).Start();
    
                // Accept the next available, pending connection request. 
                // Shutting down the listener allows a clean exit. 
                // This method returns null.
                while (true)
                {
                    var relayConnection = await listener.AcceptConnectionAsync();
                    if (relayConnection == null)
                    {
                        break;
                    }
    
                    ProcessMessagesOnConnection(relayConnection, cts);
                }
    
                // Close the listener after you exit the processing loop.
                await listener.CloseAsync(cts.Token);
            }
    
            private static async void ProcessMessagesOnConnection(HybridConnectionStream relayConnection, CancellationTokenSource cts)
            {
                Console.WriteLine("New session");
    
                // The connection is a fully bidrectional stream. 
                // Put a stream reader and a stream writer over it.  
                // This allows you to read UTF-8 text that comes from 
                // the sender, and to write text replies back.
                var reader = new StreamReader(relayConnection);
                var writer = new StreamWriter(relayConnection) { AutoFlush = true };
                while (!cts.IsCancellationRequested)
                {
                    try
                    {
                        // Read a line of input until a newline is encountered.
                        var line = await reader.ReadLineAsync();
    
                        if (string.IsNullOrEmpty(line))
                        {
                            // If there's no input data, signal that 
                            // you will no longer send data on this connection.
                            // Then, break out of the processing loop.
                            await relayConnection.ShutdownAsync(cts.Token);
                            break;
                        }
    
                        // Write the line on the console.
                        Console.WriteLine(line);
    
                        // Write the line back to the client, prepended with "Echo:"
                        await writer.WriteLineAsync($"Echo: {line}");
                    }
                    catch (IOException)
                    {
                        // Catch an I/O exception. This likely occurred when
                        // the client disconnected.
                        Console.WriteLine("Client closed connection");
                        break;
                    }
                }
    
                Console.WriteLine("End session");
    
                // Close the connection.
                await relayConnection.CloseAsync(cts.Token);
            }
        }
    }
    

Vytvoření klientské aplikace (odesílatel)

Napište v sadě Visual Studio konzolovou aplikaci v jazyce C#, která bude odesílat zprávy do předávací služby.

Vytvoření konzolové aplikace

V sadě Visual Studio vytvořte nový projekt Konzolová aplikace (.NET Framework).

Přidání balíčku NuGet služby Relay

  1. Klikněte pravým tlačítkem na nově vytvořený projekt a vyberte možnost Spravovat balíčky NuGet.
  2. Vyberte Procházet a vyhledejte Microsoft.Azure.Relay. Ve výsledcích hledání vyberte Microsoft Azure Relay.
  3. Vyberte Nainstalovat a dokončete instalaci. Zavřete dialogové okno.

Napsání kódu pro odesílání zpráv

  1. Na začátku souboru Program.cs nahraďte existující příkazy using následujícími příkazy using:

    using System;
    using System.IO;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Azure.Relay;
    
  2. Do třídy Program přidejte konstanty s podrobnostmi o hybridním připojení. Zástupné symboly nahraďte hodnotami, které jste získali při vytváření hybridního připojení. Nezapomeňte použít plně kvalifikovaný obor názvů.

    // replace {RelayNamespace} with the name of your namespace
    private const string RelayNamespace = "YOUR-RELAY-NAMESPACE-NAME.servicebus.windows.net";
    
    // replace {HybridConnectionName} with the name of your hybrid connection
    private const string ConnectionName = "HYBRID-CONNECTION-NAME";
    
    // replace {SAKKeyName} with the name of your Shared Access Policies key, which is RootManageSharedAccessKey by default
    private const string KeyName = "SAS-KEY-NAME";
    
    // replace {SASKey} with the primary key of the namespace you saved earlier
    private const string Key = "SAS-KEY-VALUE";
    
  3. Do třídy Program přidejte následující metodu:

    private static async Task RunAsync()
    {
        Console.WriteLine("Enter lines of text to send to the server with ENTER");
    
        // Create a new hybrid connection client.
        var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
        var client = new HybridConnectionClient(new Uri(String.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);
    
        // Initiate the connection.
        var relayConnection = await client.CreateConnectionAsync();
    
        // Run two concurrent loops on the connection. One 
        // reads input from the console and writes it to the connection 
        // with a stream writer. The other reads lines of input from the 
        // connection with a stream reader and writes them to the console. 
        // Entering a blank line shuts down the write task after 
        // sending it to the server. The server then cleanly shuts down
        // the connection, which terminates the read task.
    
        var reads = Task.Run(async () => {
            // Initialize the stream reader over the connection.
            var reader = new StreamReader(relayConnection);
            var writer = Console.Out;
            do
            {
                // Read a full line of UTF-8 text up to newline.
                string line = await reader.ReadLineAsync();
                // If the string is empty or null, you are done.
                if (String.IsNullOrEmpty(line))
                    break;
                // Write to the console.
                await writer.WriteLineAsync(line);
            }
            while (true);
        });
    
        // Read from the console and write to the hybrid connection.
        var writes = Task.Run(async () => {
            var reader = Console.In;
            var writer = new StreamWriter(relayConnection) { AutoFlush = true };
            do
            {
                // Read a line from the console.
                string line = await reader.ReadLineAsync();
                // Write the line out, also when it's empty.
                await writer.WriteLineAsync(line);
                // Quit when the line is empty,
                if (String.IsNullOrEmpty(line))
                    break;
            }
            while (true);
        });
    
        // Wait for both tasks to finish.
        await Task.WhenAll(reads, writes);
        await relayConnection.CloseAsync(CancellationToken.None);
    }
    
  4. Ve třídě Program přidejte do metody Main následující řádek kódu.

    RunAsync().GetAwaiter().GetResult();
    

    Soubor Program.cs by měl vypadat nějak takto:

    using System;
    using System.IO;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Azure.Relay;
    
    namespace Client
    {
        class Program
        {
            private const string RelayNamespace = "{RelayNamespace}.servicebus.windows.net";
            private const string ConnectionName = "{HybridConnectionName}";
            private const string KeyName = "{SASKeyName}";
            private const string Key = "{SASKey}";
    
            static void Main(string[] args)
            {
                RunAsync().GetAwaiter().GetResult();
            }
    
            private static async Task RunAsync()
            {
                Console.WriteLine("Enter lines of text to send to the server with ENTER");
    
                // Create a new hybrid connection client.
                var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
                var client = new HybridConnectionClient(new Uri(String.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);
    
                // Initiate the connection.
                var relayConnection = await client.CreateConnectionAsync();
    
                // Run two concurrent loops on the connection. One 
                // reads input from the console and then writes it to the connection 
                // with a stream writer. The other reads lines of input from the 
                // connection with a stream reader and then writes them to the console. 
                // Entering a blank line shuts down the write task after 
                // sending it to the server. The server then cleanly shuts down
                // the connection, which terminates the read task.
    
                var reads = Task.Run(async () => {
                    // Initialize the stream reader over the connection.
                    var reader = new StreamReader(relayConnection);
                    var writer = Console.Out;
                    do
                    {
                        // Read a full line of UTF-8 text up to newline.
                        string line = await reader.ReadLineAsync();
                        // If the string is empty or null, you are done.
                        if (String.IsNullOrEmpty(line))
                            break;
                        // Write to the console.
                        await writer.WriteLineAsync(line);
                    }
                    while (true);
                });
    
                // Read from the console and write to the hybrid connection.
                var writes = Task.Run(async () => {
                    var reader = Console.In;
                    var writer = new StreamWriter(relayConnection) { AutoFlush = true };
                    do
                    {
                        // Read a line from the console.
                        string line = await reader.ReadLineAsync();
                        // Write the line out, also when it's empty.
                        await writer.WriteLineAsync(line);
                        // Quit when the line is empty.
                        if (String.IsNullOrEmpty(line))
                            break;
                    }
                    while (true);
                });
    
                // Wait for both tasks to finish.
                await Task.WhenAll(reads, writes);
                await relayConnection.CloseAsync(CancellationToken.None);
            }
        }
    }
    

Poznámka:

Ukázkový kód v tomto článku používá připojovací řetězec k ověření v oboru názvů Služby Azure Relay, aby byl kurz jednoduchý. Doporučujeme používat ověřování Microsoft Entra ID v produkčních prostředích místo použití připojovací řetězec nebo sdílených přístupových podpisů, které se dají snadněji ohrozit. Podrobné informace a vzorový kód pro použití ověřování POMOCÍ ID Microsoft Entra najdete v tématu Ověřování a autorizace aplikace pomocí Microsoft Entra ID pro přístup k entitě Azure Relay a ověření spravované identity pomocí Microsoft Entra ID pro přístup k prostředkům Azure Relay.

Spuštění aplikací

  1. Spusťte serverovou aplikaci.

  2. Spusťte klientskou aplikaci a napište nějaký text.

  3. Ujistěte se, že konzola serverové aplikace zobrazí text, který jste zadali v klientské aplikaci.

    Okna konzoly testuje serverové i klientské aplikace.

Blahopřejeme, vytvořili jste kompletní aplikaci Hybrid Connections!

Další kroky

V tomto rychlém startu jste vytvořili klientské a serverové aplikace .NET, které k odesílání a příjmu zpráv používaly webSockety. Funkce Hybridní připojení služby Azure Relay také podporuje odesílání a přijímání zpráv pomocí protokolu HTTP. Informace o použití PROTOKOLU HTTP s hybridními připojeními Azure Relay najdete v rychlém startu HTTP.

V tomto rychlém startu jste k vytváření klientských a serverových aplikací použili rozhraní .NET Framework. Informace o psaní klientských a serverových aplikací pomocí Node.js najdete v rychlém startu Node.js WebSockets nebo v rychlém startu Node.js HTTP.