Share via


Ismerkedés a hibrid Relay-kapcsolatok websocketjeivel a .NET-ben

Ebben a rövid útmutatóban .NET-küldő- és fogadóalkalmazásokat hoz létre, amelyek hibrid Csatlakozás ions WebSockets használatával küldenek és fogadnak üzeneteket az Azure Relayben. Az Azure Relay általános megismeréséhez tekintse meg az Azure Relayt.

Ebben a rövid útmutatóban a következő lépéseket kell elvégeznie:

  1. Relay-névtér létrehozása az Azure Portal használatával.
  2. Hibrid kapcsolat létrehozása ezen a névtéren az Azure Portal használatával.
  3. Kiszolgálói (figyelő) konzolalkalmazás írása üzenetfogadási céllal.
  4. Ügyfél-konzolalkalmazás (küldő) írása üzenetküldési céllal.
  5. Alkalmazások futtatása.

Előfeltételek

Az oktatóanyag teljesítéséhez a következő előfeltételekre lesz szüksége:

Névtér létrehozása

  1. Jelentkezzen be az Azure Portalra.

  2. Válassza az Összes szolgáltatás lehetőséget a bal oldali menüben. Válassza az Integráció lehetőséget, keresse meg a Továbbítókat, vigye az egeret a Továbbítók fölé, majd válassza a Létrehozás lehetőséget.

    Screenshot showing the selection of Relays -> Create button.

  3. A Névtér létrehozása lapon kövesse az alábbi lépéseket:

    1. Válasszon egy Azure-előfizetést, amelyben létre szeretné hozni a névteret.

    2. Erőforráscsoport esetén válasszon ki egy meglévő erőforráscsoportot, amelyben elhelyezi a névteret, vagy hozzon létre egy újat.

    3. Adja meg a Relay névtér nevét.

    4. Válassza ki azt a régiót, amelyben a névteret üzemeltetni kell.

    5. Válassza a Véleményezés + létrehozás lehetőséget a lap alján.

      Screenshot showing the Create namespace page.

    6. A Véleményezés + létrehozás lapon válassza a Létrehozás lehetőséget.

    7. Néhány perc múlva megjelenik a névtér Relay lapja.

      Screenshot showing the home page for Relay namespace.

Felügyeleti hitelesítő adatok lekérése

  1. A Relay lapon válassza a megosztott hozzáférési szabályzatokat a bal oldali menüben. `

  2. A Megosztott hozzáférési szabályzatok lapon válassza a RootManageSharedAccessKey lehetőséget.

  3. Az SAS-szabályzat: RootManageSharedAccessKey területen válassza a Másolás gombot az elsődleges Csatlakozás ion-sztring mellett. Ez a művelet a vágólapra másolja a kapcsolati sztring későbbi használatra. Illessze be ezt az értéket a Jegyzettömbbe vagy egy másik ideiglenes helyre.

  4. A későbbi használat érdekében ismételje meg az előző lépést, és másolja ki és illessze be az Elsődleges kulcs értékét egy ideiglenes helyre.

    Screenshot showing the connection info for Relay namespace.

Hibrid kapcsolat létrehozása

A névtér Relay lapján kövesse az alábbi lépéseket egy hibrid kapcsolat létrehozásához.

  1. A bal oldali menü Entitások alatt válassza a Hibrid Csatlakozás ions, majd a + Hibrid Csatlakozás ion lehetőséget.

    Screenshot showing the Hybrid Connections page.

  2. A Hibrid Csatlakozás ion létrehozása lapon adja meg a hibrid kapcsolat nevét, és válassza a Létrehozás lehetőséget.

    Screenshot showing the Create Hybrid Connection page.

Kiszolgálói alkalmazás (figyelő) létrehozása

A Visual Studióban egy C# nyelven íródott konzolalkalmazást hozunk létre az üzenetek figyeléséhez és a Relay-től való fogadásához.

Konzolalkalmazás létrehozása

Hozzon létre egy új Konzolalkalmazás- (.NET-keretrendszer-) projektet a Visual Studióban.

A Relay NuGet-csomag hozzáadása

  1. Kattintson a jobb gombbal az újonnan létrehozott projektre, majd válassza a NuGet-csomagok kezelése lehetőséget.
  2. Válassza a Tallózás elemet, majd keressen rá a Microsoft.Azure.Relay kifejezésre. Válassza ki a Microsoft Azure Relay elemet a keresési eredmények közül.
  3. Kattintson a Telepítés gombra a telepítés befejezéséhez. Zárja be a párbeszédpanelt.

Kód írása az üzenetek fogadásához

  1. A Program.cs fájl elején cserélje le a meglévő using-utasításokat az alábbi using-utasításokra:

    using System;
    using System.IO;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Net;
    using Microsoft.Azure.Relay;
    
  2. Adjon állandókat a Program osztályhoz a hibrid kapcsolat részleteivel. Cserélje le a helyőrzőket a hibrid kapcsolat létrehozásakor kapott értékekre. Ügyeljen arra, hogy a teljes névtérnevet használja.

    // 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. Adja hozzá a ProcessMessagesOnConnection metódust a Program osztályhoz:

    // 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. Adja hozzá a RunAsync metódust a Program osztályhoz:

    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. Adja hozzá a következő kódsort a Main metódushoz a Program osztályban:

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

    A befejezett Program.cs fájlnak így kell kinéznie:

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

Ügyfélalkalmazás létrehozása (küldő)

A Visual Studióban egy C# nyelven íródott konzolalkalmazást hozunk létre az üzenetek Relay-be való küldéséhez.

Konzolalkalmazás létrehozása

Hozzon létre egy új Konzolalkalmazás- (.NET-keretrendszer-) projektet a Visual Studióban.

A Relay NuGet-csomag hozzáadása

  1. Kattintson a jobb gombbal az újonnan létrehozott projektre, majd válassza a NuGet-csomagok kezelése lehetőséget.
  2. Válassza a Tallózás elemet, majd keressen rá a Microsoft.Azure.Relay kifejezésre. Válassza ki a Microsoft Azure Relay elemet a keresési eredmények közül.
  3. Kattintson a Telepítés gombra a telepítés befejezéséhez. Zárja be a párbeszédpanelt.

Kód írása az üzenetek küldéséhez

  1. A Program.cs fájl elején cserélje le a meglévő using-utasításokat az alábbi using-utasításokra:

    using System;
    using System.IO;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Azure.Relay;
    
  2. Adjon állandókat a Program osztályhoz a hibrid kapcsolat részleteivel. Cserélje le a helyőrzőket a hibrid kapcsolat létrehozásakor kapott értékekre. Ügyeljen arra, hogy a teljes névtérnevet használja.

    // 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. Adja hozzá a következő metódust a Program osztályhoz:

    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. Adja hozzá a következő kódsort a Main metódushoz a Program osztályban.

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

    A Program.cs fájlnak így kell kinéznie:

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

Az alkalmazások futtatása

  1. Futtassa a kiszolgálóalkalmazást.

  2. Futtassa az ügyfélalkalmazást, és adjon meg szöveget.

  3. Győződjön meg arról, hogy az alkalmazás konzolja megjeleníti a szöveget, amely az ügyfélalkalmazásban lett megadva.

    Console windows testing both the server and client applications.

Gratulálunk, létrehozott egy teljes hibrid Csatlakozás ions alkalmazást!

Következő lépések

Ebben a rövid útmutatóban létrehozott egy .NET-ügyfél- és kiszolgálóalkalmazást, amely WebSockets használatával küldött és fogadott üzeneteket. Az Azure Relay hibrid Csatlakozás ions funkciója a HTTP használatával is támogatja az üzenetek küldését és fogadását. Ha meg szeretné tudni, hogyan használhatja a HTTP-t az Azure Relay hibrid Csatlakozás ions használatával, tekintse meg a HTTP rövid útmutatóját.

Ebben a rövid útmutatóban .NET-keretrendszer használt ügyfél- és kiszolgálóalkalmazások létrehozásához. Ha tudni szeretné, hogyan írhat ügyfél- és kiszolgálóalkalmazásokat a Node.js használatával, tekintse meg a Node.js WebSockets rövid útmutatót vagy a Node.js HTTP rövid útmutatót.