.NET’te Geçiş Karma Bağlantıları Web Yuvaları ile çalışmaya başlama

Bu hızlı başlangıçta, Azure Relay'de Karma Bağlan ions WebSockets kullanarak ileti gönderip alan .NET gönderen ve alıcı uygulamaları oluşturacaksınız. Genel olarak Azure Relay hakkında bilgi edinmek için bkz . Azure Relay.

Bu hızlı başlangıçta aşağıdaki adımları uygulayacaksınız:

  1. Azure portalını kullanarak Geçiş ad alanı oluşturma.
  2. Azure portalını kullanarak o ad alanında karma bağlantı oluşturma.
  3. İleti almak için bir sunucu (dinleyici) konsol uygulaması yazma.
  4. İleti göndermek için bir istemci (gönderen) konsol uygulaması yazma.
  5. Uygulamaları çalıştırın.

Ön koşullar

Bu öğreticiyi tamamlamak için aşağıdaki önkoşulları karşılamanız gerekir:

Ad alanı oluşturma

  1. Azure Portal oturum açın.

  2. Soldaki menüden Tüm hizmetler'i seçin. Tümleştirme'yi seçin, Geçişler'i arayın, fareyi Geçişler'in üzerine getirin ve oluştur'u seçin.

    Screenshot showing the selection of Relays -> Create button.

  3. Ad alanı oluştur sayfasında şu adımları izleyin:

    1. Ad alanının oluşturulacağı bir Azure aboneliği seçin.

    2. Kaynak grubu için, ad alanının yerleştirileceği mevcut bir kaynak grubunu seçin veya yeni bir tane oluşturun.

    3. Geçiş ad alanı için bir ad girin.

    4. Ad alanınızın barındırılacağı bölgeyi seçin.

    5. Sayfanın alt kısmındaki Gözden geçir ve oluştur'u seçin.

      Screenshot showing the Create namespace page.

    6. Gözden Geçir + oluştur sayfasında Oluştur'u seçin.

    7. Birkaç dakika sonra ad alanının Geçiş sayfasını görürsünüz.

      Screenshot showing the home page for Relay namespace.

Yönetim kimlik bilgilerini alma

  1. Geçiş sayfasında, soldaki menüden Paylaşılan erişim ilkeleri'ni seçin. `

  2. Paylaşılan erişim ilkeleri sayfasında RootManageSharedAccessKey'i seçin.

  3. SAS İlkesi: RootManageSharedAccessKey altında Birincil Bağlan ion Dizesi'nin yanındaki Kopyala düğmesini seçin. Bu eylem, bağlantı dizesi daha sonra kullanmak üzere panonuza kopyalar. Bu değeri Not Defteri veya başka bir geçici konuma yapıştırın.

  4. Birincil anahtar değerini daha sonra kullanmak üzere kopyalayıp geçici bir konuma yapıştırarak önceki adımı tekrarlayın.

    Screenshot showing the connection info for Relay namespace.

Karma bağlantı oluşturma

Ad alanınızın Geçiş sayfasında, karma bağlantı oluşturmak için bu adımları izleyin.

  1. Soldaki menüde Varlıklar'ın altında Karma Bağlan ions'ı ve ardından + Karma Bağlan ion'ı seçin.

    Screenshot showing the Hybrid Connections page.

  2. Karma Bağlan oluşturma sayfasında karma bağlantı için bir ad girin ve Oluştur'u seçin.

    Screenshot showing the Create Hybrid Connection page.

Sunucu uygulaması (dinleyici) oluşturma

Geçiş hizmetinden ileti dinleyip almak için Visual Studio kullanarak bir C# konsol uygulaması yazın.

Konsol uygulaması oluşturma

Visual Studio'da yeni bir Konsol Uygulaması (.NET Framework) projesi oluşturun.

Geçiş NuGet paketini ekleme

  1. Yeni oluşturulan projeye sağ tıklayıp NuGet Paketlerini Yönet'i seçin.
  2. Göz at'ı seçip Microsoft.Azure.Relay araması yapın. Arama sonuçlarında Microsoft Azure Geçişi'ni seçin.
  3. Yüklemeyi tamamlamak için Yükle'yi seçin. İletişim kutusunu kapatın.

İleti almak için kod yazma

  1. Program.cs dosyasının üst tarafındaki using deyimlerini aşağıdaki using deyimleriyle değiştirin:

    using System;
    using System.IO;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Net;
    using Microsoft.Azure.Relay;
    
  2. Karma bağlantı ayrıntıları için sabitleri Program sınıfına ekleyin. Yer tutucuları, karma bağlantıyı oluştururken aldığınız değerlerle değiştirin. Tam ad alanı adını kullandığınızdan emin olun.

    // 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. ProcessMessagesOnConnection yönetimini Program sınıfına ekleyin:

    // 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. RunAsync yönetimini Program sınıfına ekleyin:

    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. Aşağıdaki kod satırını Program sınıfındaki Main yöntemine ekleyin:

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

    Tamamlanmış Program.cs dosyası aşağıdaki gibi görünmelidir:

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

İstemci uygulaması (gönderici) oluşturma

Geçiş hizmetine ileti göndermek Visual Studio kullanarak bir C# konsol uygulaması yazın.

Konsol uygulaması oluşturma

Visual Studio'da yeni bir Konsol Uygulaması (.NET Framework) projesi oluşturun.

Geçiş NuGet paketini ekleme

  1. Yeni oluşturulan projeye sağ tıklayıp NuGet Paketlerini Yönet'i seçin.
  2. Göz at'ı seçip Microsoft.Azure.Relay araması yapın. Arama sonuçlarında Microsoft Azure Geçişi'ni seçin.
  3. Yüklemeyi tamamlamak için Yükle'yi seçin. İletişim kutusunu kapatın.

İleti göndermek için kod yazma

  1. Program.cs dosyasının üst tarafındaki using deyimlerini aşağıdaki using deyimleriyle değiştirin:

    using System;
    using System.IO;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Azure.Relay;
    
  2. Karma bağlantı ayrıntıları için sabitleri Program sınıfına ekleyin. Yer tutucuları, karma bağlantıyı oluştururken aldığınız değerlerle değiştirin. Tam ad alanı adını kullandığınızdan emin olun.

    // 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. Program sınıfına aşağıdaki yöntemi ekleyin:

    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. Aşağıdaki kod satırını Program sınıfındaki Main yöntemine ekleyin.

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

    Program.cs aşağıdaki gibi görünmelidir:

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

Uygulamaları çalıştırma

  1. Sunucu uygulamasını çalıştırın.

  2. İstemci uygulamasını çalıştırın ve metin girin.

  3. Sunucu uygulama konsolunun istemci uygulamasına girilen metni görüntülediğinden emin olun.

    Console windows testing both the server and client applications.

Tebrikler, eksiksiz bir Karma Bağlan ions uygulaması oluşturdunuz!

Sonraki adımlar

Bu hızlı başlangıçta, ileti göndermek ve almak için WebSockets kullanan .NET istemci ve sunucu uygulamaları oluşturdunuz. Azure Relay'in Karma Bağlan ions özelliği, ileti göndermek ve almak için HTTP kullanmayı da destekler. Http'yi Azure Relay Karma Bağlan ions ile kullanmayı öğrenmek için bkz. HTTP hızlı başlangıcı.

Bu hızlı başlangıçta istemci ve sunucu uygulamaları oluşturmak için .NET Framework kullandınız. Node.js kullanarak istemci ve sunucu uygulamaları yazmayı öğrenmek için Bkz . Node.js WebSockets hızlı başlangıcı veya Node.js HTTP hızlı başlangıcı.