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í hybridních Připojení ionů WebSocket ve službě 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.

Předpoklady

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.

    Screenshot showing the selection of Relays -> Create button.

  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.

      Screenshot showing the Create namespace page.

    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ů.

      Screenshot showing the home page for Relay namespace.

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 řetězce Připojení ionu. 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í.

    Screenshot showing the connection info for Relay namespace.

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í ions a pak vyberte + Hybridní Připojení ion.

    Screenshot showing the Hybrid Connections page.

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

    Screenshot showing the Create Hybrid Connection page.

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

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.

    Console windows testing both the server and client applications.

Blahopřejeme, vytvořili jste kompletní hybridní Připojení ionovou aplikaci.

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ích Připojení ionů služby Azure Relay také podporuje odesílání a přijímání zpráv pomocí protokolu HTTP. Informace o používání protokolu HTTP s hybridními Připojení 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 tom, jak psát klientské a serverové aplikace pomocí Node.js, najdete v rychlém startu Node.js WebSockets nebo v rychlém startu HTTP Node.js.