예제 #1
0
        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"); };
            // Establish the control channel to the Azure Relay service
            await listener.OpenAsync(cts.Token);

            Console.WriteLine("Server listening");
            // Providing callback for 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.
            while (true)
            {
                var relayConnection = await listener.AcceptConnectionAsync();

                if (relayConnection == null)
                {
                    break;
                }

                ProcessMessagesOnConnection(relayConnection, cts);
            }

// Close the listener after we exit the processing loop
            await listener.CloseAsync(cts.Token);
        }
예제 #2
0
        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);

            listener.Connecting += (o, e) => { Console.WriteLine("Connecting ..."); };
            listener.Offline    += (o, e) => { Console.WriteLine("Offine"); };
            listener.Online     += (o, e) => { Console.WriteLine("Onine"); };

            await listener.OpenAsync(cts.Token);

            Console.WriteLine("Server Listening ...");

            cts.Token.Register(() => listener.CloseAsync(CancellationToken.None));

            new Task(() => Console.In.ReadLineAsync().ContinueWith((s) => { cts.Cancel(); })).Start();

            while (true)
            {
                var relayConnection = await listener.AcceptConnectionAsync();

                if (relayConnection == null)
                {
                    break;
                }

                ProcessMessagesOnConnection(relayConnection, cts);
            }

            await listener.CloseAsync(cts.Token);
        }
예제 #3
0
        private static async Task RunAsync()
        {
            var cts = new CancellationTokenSource();

            //  var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, myKey);
            //  var listener = new HybridConnectionListener(new Uri(string.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);

            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, myKey);
            var listener      = new HybridConnectionListener(new Uri(String.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);


            // Subscribe to the status events
            Console.BackgroundColor = ConsoleColor.Yellow;
            Console.ForegroundColor = ConsoleColor.Black;
            listener.Connecting    += (o, e) => { Console.WriteLine("Connecting"); };
            listener.Offline       += (o, e) => { Console.WriteLine("Offline"); };
            listener.Online        += (o, e) => { Console.WriteLine("Online"); };

            // Opening the listener will establish the control channel to
            // the Azure Relay service. The control channel will be continuously
            // maintained and reestablished when connectivity is disrupted.
            await listener.OpenAsync(cts.Token);

            Console.BackgroundColor = ConsoleColor.Yellow;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("Server " + RelayNamespace + " is listening...");
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;

            // Providing callback for 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 will allow a clean exit with
            // this method returning null
            while (true)
            {
                var relayConnection = await listener.AcceptConnectionAsync();

                if (relayConnection == null)
                {
                    break;
                }

                ProcessMessagesOnConnection(relayConnection, cts);
            }

            // Close the listener after we exit the processing loop
            await listener.CloseAsync(cts.Token);
        }
예제 #4
0
        public void TestSendingStringToHybridConnectionSwitchboard()
        {
            string connectionName  = "TestSendingStringToHybridConnectionSwitchboard";
            string responseMessage = "Well hello to you!!";

            CreateHybridConnection(connectionName);
            HybridConnectionListener listener = null;

            try
            {
                listener = CreateHybridListener(connectionName, responseMessage);
                ILocalSwitchboard switchBoard = new Telegraphy.Azure.Relay.Hybrid.HybridConnectionSwitchboard(3, Connections.HybridRelayConnectionString, connectionName);
                IOperator         localOP     = new LocalQueueOperator(switchBoard);
                Telegraph.Instance.Register(localOP);
                Telegraph.Instance.Register(typeof(Exception), FailOnException);

                // We want to send the byte[] to the localOP which will forward calls to the hybrid connection switchboard operator
                Telegraph.Instance.Register <string>(localOP);

                string responseString = (string)Telegraph.Instance.Ask("Foo").Result.Message;
                Assert.IsTrue(responseString.Equals(responseMessage));
            }
            finally
            {
                Telegraph.Instance.UnRegisterAll();
                try { listener?.CloseAsync().Wait(); } catch (Exception) { }
                DeleteHybridConnection(connectionName);
            }
        }
예제 #5
0
        public async Task Stop()
        {
            _eventGridEvents.Clear();
            await _listener.CloseAsync();

            _stopThread = true;
        }
예제 #6
0
        private async Task RunAsync()
        {
            // Create a new hybrid connection client
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, key);
            var listener      = new HybridConnectionListener(new Uri($"sb://{relayNamespace}/{connectionName}"), tokenProvider);

            // Open the listener and register it in Service Bus
            var cts = new CancellationTokenSource();
            await listener.OpenAsync(cts.Token);

            // Callback for cancellation token that will close the listener
            cts.Token.Register(() => listener.CloseAsync(CancellationToken.None));

            await Listen(listener, cts)
            .ContinueWith((t) => listener.CloseAsync(cts.Token));
        }
예제 #7
0
        async Task ListenerShutdownWithPendingAcceptsTest(EndpointTestType endpointTestType)
        {
            HybridConnectionListener listener = null;

            try
            {
                listener = GetHybridConnectionListener(endpointTestType);
                var client = GetHybridConnectionClient(endpointTestType);

                TestUtility.Log($"Opening {listener}");
                await listener.OpenAsync(TimeSpan.FromSeconds(20));

                var acceptTasks = new List <Task <HybridConnectionStream> >(600);
                TestUtility.Log($"Calling listener.AcceptConnectionAsync() {acceptTasks.Capacity} times");
                for (int i = 0; i < acceptTasks.Capacity; i++)
                {
                    acceptTasks.Add(listener.AcceptConnectionAsync());
                    Assert.False(acceptTasks[i].IsCompleted);
                }

                TestUtility.Log($"Closing {listener}");
                await listener.CloseAsync(TimeSpan.FromSeconds(10));

                listener = null;
                for (int i = 0; i < acceptTasks.Count; i++)
                {
                    Assert.True(acceptTasks[i].Wait(TimeSpan.FromSeconds(5)));
                    Assert.Null(acceptTasks[i].Result);
                }
            }
            finally
            {
                await this.SafeCloseAsync(listener);
            }
        }
예제 #8
0
        public void TestSubscribingToHybridConnection()
        {
            string connectionName  = "TestSubscribingToHybridConnection";
            string responseMessage = "Well hello to you!!";

            CreateHybridConnection(connectionName);
            HybridConnectionListener listener = null;

            try
            {
                //listener = CreateHybridListener(connectionName, responseMessage);
                IOperator localOP = new Telegraphy.Azure.Relay.Hybrid.HybridConnectionSubscriptionOperator <string>(Connections.HybridRelayConnectionString, connectionName);

                bool recieved = false;
                Telegraph.Instance.Register <string>(localOP, (msgString) =>
                {
                    recieved = true;
                    Console.WriteLine(msgString);
                    Assert.IsTrue(responseMessage.Equals(responseMessage));
                });
                Telegraph.Instance.Register(typeof(Exception), FailOnException);

                var client = new Telegraphy.Azure.Relay.Hybrid.RecieveResponseFromRequest <string, string>(Connections.HybridRelayConnectionString, connectionName);
                (client as IActor).OnMessageRecieved(responseMessage.ToActorMessage());

                System.Threading.Thread.Sleep(3000);
                Assert.IsTrue(recieved);
            }
            finally
            {
                Telegraph.Instance.UnRegisterAll();
                try { listener?.CloseAsync().Wait(); } catch (Exception) { }
                DeleteHybridConnection(connectionName);
            }
        }
 private void StopListener()
 {
     if (null != listener)
     {
         listener.CloseAsync().Wait();
     }
 }
예제 #10
0
        public void TestSendingStringToHybridConnection()
        {
            string relayName       = "TestSendingStringToHybridConnection";
            string responseMessage = "Well hello to you!!";

            CreateHybridConnection(relayName);
            Telegraph.Instance.Register(typeof(Exception), FailOnException);
            HybridConnectionListener listener = null;

            try
            {
                listener = CreateHybridListener(relayName, responseMessage);
                var relayConnection = new Telegraphy.Azure.Relay.Hybrid.RecieveResponseFromRequest <string, string>(Connections.HybridRelayConnectionString, relayName);

                Telegraph.Instance.Register <string, Telegraphy.Azure.Relay.Hybrid.RecieveResponseFromRequest <string, string> >(() => relayConnection);
                var  result  = Telegraph.Instance.Ask("Hello");
                bool success = result.Wait(System.Diagnostics.Debugger.IsAttached ? TimeSpan.FromMinutes(30) : TimeSpan.FromSeconds(30));
                Assert.IsTrue(success);

                if (success)
                {
                    Assert.IsTrue(result.Result.Message.Equals(responseMessage));
                }
            }
            finally
            {
                Telegraph.Instance.UnRegisterAll();
                try { listener?.CloseAsync().Wait(); } catch (Exception) { }
                DeleteRelay(relayName);
            }
        }
예제 #11
0
        private static async Task RunAsync()
        {
            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"); };

            // Provide an HTTP request handler
            listener.RequestHandler = ProcessRelayedHttpRequest;

            // 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();

            Console.WriteLine("Server listening");

            // Start a new thread that will continuously read the console.
            await Console.In.ReadLineAsync();

            // Close the listener after you exit the processing loop.
            await listener.CloseAsync();
        }
        public override Task StopAsync()
        {
            var closeTask = listener.CloseAsync(TimeSpan.FromSeconds(10));

            shutdownTokenSource.Cancel();
            return(acceptTask);
        }
예제 #13
0
        public void TestSendingBytesoHybridConnection()
        {
            string relayName       = "TestSendingBytesoHybridConnection";
            string responseMessage = "Well hello to you!!";
            string askMessage      = "Hello";

            byte[] msgBytes = Encoding.UTF8.GetBytes(askMessage);
            CreateHybridConnection(relayName);
            Telegraph.Instance.Register(typeof(Exception), FailOnException);
            HybridConnectionListener listener = null;

            try
            {
                listener = CreateHybridListener(relayName, responseMessage);
                var relayConnection = new Telegraphy.Azure.Relay.Hybrid.RecieveResponseFromRequest <byte[], byte[]>(Connections.HybridRelayConnectionString, relayName);

                Telegraph.Instance.Register <byte[], Telegraphy.Azure.Relay.Hybrid.RecieveResponseFromRequest <byte[], byte[]> >(() => relayConnection);
                var  result  = Telegraph.Instance.Ask(msgBytes.ToActorMessage());
                bool success = result.Wait(System.Diagnostics.Debugger.IsAttached ? TimeSpan.FromMinutes(30) : TimeSpan.FromSeconds(30));
                Assert.IsTrue(success);

                if (success)
                {
                    Assert.IsTrue(Encoding.UTF8.GetString(result.Result.Message as byte[]).Equals(responseMessage));
                }
            }
            finally
            {
                try { listener?.CloseAsync().Wait(); } catch (Exception) { }
                DeleteRelay(relayName);
            }
        }
예제 #14
0
        async Task RawWebSocketSenderTest(EndpointTestType endpointTestType)
        {
            HybridConnectionListener listener = null;

            try
            {
                listener = GetHybridConnectionListener(endpointTestType);

                var clientWebSocket = new ClientWebSocket();
                var wssUri          = await GetWebSocketConnectionUri(endpointTestType);

                using (var cancelSource = new CancellationTokenSource(TimeSpan.FromMinutes(1)))
                {
                    TestUtility.Log($"Opening {listener}");
                    await listener.OpenAsync(cancelSource.Token);

                    await clientWebSocket.ConnectAsync(wssUri, cancelSource.Token);

                    var listenerStream = await listener.AcceptConnectionAsync();

                    TestUtility.Log("Client and Listener are connected!");
                    Assert.Null(clientWebSocket.SubProtocol);

                    byte[] sendBuffer = this.CreateBuffer(1024, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
                    await clientWebSocket.SendAsync(new ArraySegment <byte>(sendBuffer), WebSocketMessageType.Binary, true, cancelSource.Token);

                    TestUtility.Log($"clientWebSocket wrote {sendBuffer.Length} bytes");

                    byte[] readBuffer = new byte[sendBuffer.Length];
                    await this.ReadCountBytesAsync(listenerStream, readBuffer, 0, readBuffer.Length, TimeSpan.FromSeconds(30));

                    Assert.Equal(sendBuffer, readBuffer);

                    TestUtility.Log("Calling clientStream.CloseAsync");
                    var clientStreamCloseTask = clientWebSocket.CloseAsync(WebSocketCloseStatus.EndpointUnavailable, "From Test Code", cancelSource.Token);
                    TestUtility.Log("Reading from listenerStream");
                    int bytesRead = await this.SafeReadAsync(listenerStream, readBuffer, 0, readBuffer.Length);

                    TestUtility.Log($"listenerStream.Read returned {bytesRead} bytes");
                    Assert.Equal(0, bytesRead);

                    TestUtility.Log("Calling listenerStream.CloseAsync");
                    var   listenerStreamCloseTask = listenerStream.CloseAsync(cancelSource.Token);
                    await listenerStreamCloseTask;
                    TestUtility.Log("Calling listenerStream.CloseAsync completed");
                    await clientStreamCloseTask;
                    TestUtility.Log("Calling clientStream.CloseAsync completed");

                    TestUtility.Log($"Closing {listener}");
                    await listener.CloseAsync(TimeSpan.FromSeconds(10));

                    listener = null;
                }
            }
            finally
            {
                await this.SafeCloseAsync(listener);
            }
        }
예제 #15
0
        static async Task RunAsync(string[] args)
        {
            var ns      = "<your namespace url from shared access policy- just the fdqn no protocols>";
            var hc      = "<your hybrid connection name - can be found in portal under the relay>"; //This is the name for the current store - one per store to be cofigured when running the service in the store
            var keyname = "<shared access key name such as RootManageSharedAccessKey>";
            var key     = "<key value from the shared access policies>";

            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyname, key);
            var listener      = new HybridConnectionListener(new Uri(string.Format("sb://{0}/{1}", ns, hc)), 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"); };

            // Provide an HTTP request handler
            listener.RequestHandler = (context) =>
            {
                // Do something with context.Request.Url, HttpMethod, Headers, InputStream...
                var contextRequest            = context.Request;
                System.IO.Stream       body   = contextRequest.InputStream;
                System.IO.StreamReader reader = new System.IO.StreamReader(body, Encoding.UTF8);
                string targetUrl = reader.ReadToEnd();
                body.Close();

                context.Response.StatusCode        = HttpStatusCode.OK;
                context.Response.StatusDescription = "OK";
                string result = "";

                using (var sw = new StreamWriter(context.Response.OutputStream))
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUrl);
                    request.Method    = "Get";
                    request.KeepAlive = true;
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
                    {
                        result = sr.ReadToEnd();
                    }

                    Console.WriteLine(result);
                    sw.WriteLine(result);
                }

                context.Response.Close();
            };
            // 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();

            Console.WriteLine("Server listening");

            // Start a new thread that will continuously read the console.
            await Console.In.ReadLineAsync();

            // Close the listener
            await listener.CloseAsync();
        }
예제 #16
0
        static async Task RunAsync(string[] args)
        {
            if (args.Length < 4)
            {
                Console.WriteLine("dotnet server [ns] [hc] [keyname] [key]");
                return;
            }

            var ns      = args[0];
            var hc      = args[1];
            var keyname = args[2];
            var key     = args[3];

            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyname, key);
            var listener      = new HybridConnectionListener(new Uri(string.Format("sb://{0}/{1}", ns, hc)), tokenProvider);

            // TODO:
            // use this code (line 36) to hard code a specific proxy URL.
            //var webProxy = new WebProxy("http://192.168.1.140:808");

            // TODO:
            // use this code (line 40) to use the system settings for the user running the code. Lines 40, 41 were added to original sample
            var webProxy = HttpWebRequest.DefaultWebProxy;

            listener.Proxy = webProxy;

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

            // Provide an HTTP request handler
            listener.RequestHandler = (context) =>
            {
                // Do something with context.Request.Url, HttpMethod, Headers, InputStream...
                context.Response.StatusCode        = HttpStatusCode.OK;
                context.Response.StatusDescription = "OK";
                using (var sw = new StreamWriter(context.Response.OutputStream))
                {
                    sw.WriteLine("hello client, this is server speaking!");
                }

                // The context MUST be closed here
                context.Response.Close();
            };

            // 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();

            Console.WriteLine("Server listening");

            // Start a new thread that will continuously read the console.
            await Console.In.ReadLineAsync();

            // Close the listener
            await listener.CloseAsync();
        }
        public void Stop()
        {
            _log.Information("Relay: {idx}:{relay}. Closing relay listener connection", _forwarderIdx, _relayListener.Address);

            _tunnelFactory.Dispose();

            _relayListener.CloseAsync(CancellationToken.None).GetAwaiter().GetResult();
        }
예제 #18
0
        static async Task RunAsync(string[] args)
        {
            if (args.Length < 4)
            {
                Console.WriteLine("dotnet server [ns] [hc] [keyname] [key]");
                return;
            }

            var ns      = args[0];
            var hc      = args[1];
            var keyname = args[2];
            var key     = args[3];

            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyname, key);
            var listener      = new HybridConnectionListener(new Uri(string.Format("sb://{0}/{1}", ns, hc)), 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"); };

            // Provide an HTTP request handler
            listener.RequestHandler = async(context) =>
            {
                // Do something with context.Request.Url, HttpMethod, Headers, InputStream...
                Console.WriteLine();
                Console.WriteLine("=====HEADERS=====");
                Console.WriteLine(context.Request.Headers.ToString());
                Console.WriteLine("=====BODY=====");
                using (var sr = new StreamReader(context.Request.InputStream))
                {
                    Console.WriteLine(await sr.ReadToEndAsync());
                }

                context.Response.StatusCode        = HttpStatusCode.OK;
                context.Response.StatusDescription = "OK";
                using (var sw = new StreamWriter(context.Response.OutputStream))
                {
                    sw.WriteLine("hello!");
                }

                // The context MUST be closed here
                context.Response.Close();
            };

            // 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();

            Console.WriteLine("Server listening");

            // Start a new thread that will continuously read the console.
            await Console.In.ReadLineAsync();

            // Close the listener
            await listener.CloseAsync();
        }
예제 #19
0
        private async Task RunAsync()
        {
            _cts = new CancellationTokenSource();

            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(_conn.SharedAccessKeyName, _conn.SharedAccessKey);
            var listener      = new HybridConnectionListener(_conn.Endpoint, tokenProvider);

            // Subscribe to the status events
            listener.Connecting += Listener_Connecting;
            listener.Offline    += Listener_Offline;
            listener.Online     += Listener_Online;

            // Opening the listener will establish the control channel to
            // the Azure Relay service. The control channel will be continuously
            // maintained and reestablished when connectivity is disrupted.
            await listener.OpenAsync(_cts.Token);

            Console.WriteLine("Server listening");

            // Providing callback for 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 will allow a clean exit with
            // this method returning null
            while (true)
            {
                var relayConnection = await listener.AcceptConnectionAsync();

                if (relayConnection == null)
                {
                    break;
                }

                ProcessMessagesOnConnection(relayConnection, _cts);
            }

            // Close the listener after we exit the processing loop
            await listener.CloseAsync(_cts.Token);
        }
        async Task EmptyRequestEmptyResponse(EndpointTestType endpointTestType)
        {
            var cts = new CancellationTokenSource(TimeSpan.FromSeconds(60));
            HybridConnectionListener listener = this.GetHybridConnectionListener(endpointTestType);

            try
            {
                await listener.OpenAsync(cts.Token);

                listener.RequestHandler = async(context) =>
                {
                    TestUtility.Log($"RequestHandler: {context.Request.HttpMethod} {context.Request.Url}");
                    await context.Response.CloseAsync();
                };

                RelayConnectionStringBuilder connectionString = GetConnectionStringBuilder(endpointTestType);
                Uri endpointUri   = connectionString.Endpoint;
                Uri hybridHttpUri = new UriBuilder("https://", endpointUri.Host, endpointUri.Port, connectionString.EntityPath).Uri;

                using (var client = new HttpClient {
                    BaseAddress = hybridHttpUri
                })
                {
                    client.DefaultRequestHeaders.ExpectContinue = false;

                    var getRequest = new HttpRequestMessage();
                    getRequest.Method = HttpMethod.Get;
                    await AddAuthorizationHeader(connectionString, getRequest, hybridHttpUri);

                    LogRequest(getRequest, client);
                    using (HttpResponseMessage response = await client.SendAsync(getRequest))
                    {
                        LogResponse(response);
                        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                        Assert.Equal(0, response.Content.ReadAsStreamAsync().Result.Length);
                    }

                    var postRequest = new HttpRequestMessage();
                    postRequest.Method = HttpMethod.Post;
                    await AddAuthorizationHeader(connectionString, postRequest, hybridHttpUri);

                    LogRequest(postRequest, client);
                    using (HttpResponseMessage response = await client.SendAsync(postRequest))
                    {
                        LogResponse(response);
                        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                        Assert.Equal(0, response.Content.ReadAsStreamAsync().Result.Length);
                    }
                }

                await listener.CloseAsync(cts.Token);
            }
            finally
            {
                await SafeCloseAsync(listener);
            }
        }
        async Task Verbs()
        {
            var endpointTestType = EndpointTestType.Authenticated;
            HybridConnectionListener listener = this.GetHybridConnectionListener(endpointTestType);

            try
            {
                RelayConnectionStringBuilder connectionString = GetConnectionStringBuilder(endpointTestType);
                Uri endpointUri = connectionString.Endpoint;

                TestUtility.Log("Calling HybridConnectionListener.Open");
                await listener.OpenAsync(TimeSpan.FromSeconds(30));

                Uri hybridHttpUri = new UriBuilder("https://", endpointUri.Host, endpointUri.Port, connectionString.EntityPath).Uri;
                using (var client = new HttpClient {
                    BaseAddress = hybridHttpUri
                })
                {
                    client.DefaultRequestHeaders.ExpectContinue = false;

                    HttpMethod[] methods = new HttpMethod[]
                    {
                        HttpMethod.Delete, HttpMethod.Get, HttpMethod.Head, HttpMethod.Options, HttpMethod.Post, HttpMethod.Put, HttpMethod.Trace
                    };

                    foreach (HttpMethod method in methods)
                    {
                        TestUtility.Log($"Testing HTTP Verb: {method}");
                        string actualMethod = string.Empty;
                        listener.RequestHandler = (context) =>
                        {
                            TestUtility.Log($"RequestHandler: {context.Request.HttpMethod} {context.Request.Url}");
                            actualMethod = context.Request.HttpMethod;
                            context.Response.Close();
                        };

                        var request = new HttpRequestMessage();
                        await AddAuthorizationHeader(connectionString, request, hybridHttpUri);

                        request.Method = method;
                        LogRequestLine(request, client);
                        using (HttpResponseMessage response = await client.SendAsync(request))
                        {
                            TestUtility.Log($"Response: HTTP/{response.Version} {(int)response.StatusCode} {response.ReasonPhrase}");
                            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                            Assert.Equal(method.Method, actualMethod);
                        }
                    }
                }

                await listener.CloseAsync(TimeSpan.FromSeconds(10));
            }
            finally
            {
                await SafeCloseAsync(listener);
            }
        }
        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("Listener is setup and ready for messages");

            // 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.
            // If anything is entered on console. it will shutdown this application
            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);
        }
예제 #23
0
        async Task ClientShutdownTest(EndpointTestType endpointTestType)
        {
            HybridConnectionListener listener = null;

            try
            {
                listener = GetHybridConnectionListener(endpointTestType);
                var client = GetHybridConnectionClient(endpointTestType);

                TestUtility.Log($"Opening {listener}");
                await listener.OpenAsync(TimeSpan.FromSeconds(30));

                var clientStream = await client.CreateConnectionAsync();

                var listenerStream = await listener.AcceptConnectionAsync();

                TestUtility.Log("Client and Listener HybridStreams are connected!");

                byte[] sendBuffer = this.CreateBuffer(1024, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
                await clientStream.WriteAsync(sendBuffer, 0, sendBuffer.Length);

                TestUtility.Log($"clientStream wrote {sendBuffer.Length} bytes");

                byte[] readBuffer = new byte[sendBuffer.Length];
                await this.ReadCountBytesAsync(listenerStream, readBuffer, 0, readBuffer.Length, TimeSpan.FromSeconds(30));

                Assert.Equal(sendBuffer, readBuffer);

                TestUtility.Log("Calling clientStream.Shutdown");
                clientStream.Shutdown();
                int bytesRead = await this.SafeReadAsync(listenerStream, readBuffer, 0, readBuffer.Length);

                TestUtility.Log($"listenerStream.Read returned {bytesRead} bytes");
                Assert.Equal(0, bytesRead);

                TestUtility.Log("Calling listenerStream.Shutdown and Dispose");
                listenerStream.Shutdown();
                listenerStream.Dispose();
                bytesRead = await this.SafeReadAsync(clientStream, readBuffer, 0, readBuffer.Length);

                TestUtility.Log($"clientStream.Read returned {bytesRead} bytes");
                Assert.Equal(0, bytesRead);

                TestUtility.Log("Calling clientStream.Dispose");
                clientStream.Dispose();

                TestUtility.Log($"Closing {listener}");
                await listener.CloseAsync(TimeSpan.FromSeconds(10));

                listener = null;
            }
            finally
            {
                await this.SafeCloseAsync(listener);
            }
        }
예제 #24
0
        private static async Task RunAsync()
        {
            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"); };

            // Provide an HTTP request handler
            listener.RequestHandler = (context) =>
            {
                if (context.Request.HttpMethod.Contains("POST"))
                {
                    // Do something with context.Request.Url, HttpMethod, Headers, InputStream...
                    context.Response.StatusCode        = HttpStatusCode.OK;
                    context.Response.StatusDescription = "OK";
                    var body = new StreamReader(context.Request.InputStream).ReadToEnd();
                    using (var sw = new StreamWriter(context.Response.OutputStream))
                    {
                        sw.WriteLine("hello");
                    }
                }

                if (context.Request.HttpMethod.Contains("GET"))
                {
                    // Do something with context.Request.Url, HttpMethod, Headers, InputStream...
                    context.Response.StatusCode        = HttpStatusCode.OK;
                    context.Response.StatusDescription = "OK";
                    using (var sw = new StreamWriter(context.Response.OutputStream))
                    {
                        sw.WriteLine("world!");
                    }
                }



                // The context MUST be closed here
                context.Response.Close();
            };

            // 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();

            Console.WriteLine("Server listening");

            // Start a new thread that will continuously read the console.
            await Console.In.ReadLineAsync();

            // Close the listener after you exit the processing loop.
            await listener.CloseAsync();
        }
예제 #25
0
        async Task HybridConnectionTest(EndpointTestType endpointTestType, bool useBuiltInClientWebSocket)
        {
            HybridConnectionListener listener = null;

            try
            {
                listener = this.GetHybridConnectionListener(endpointTestType);
                listener.UseBuiltInClientWebSocket = useBuiltInClientWebSocket;
                var client = GetHybridConnectionClient(endpointTestType);
                client.UseBuiltInClientWebSocket = useBuiltInClientWebSocket;

                TestUtility.Log($"Opening {listener}");
                await listener.OpenAsync(TimeSpan.FromSeconds(30));

                var clientStream = await client.CreateConnectionAsync();

                var listenerStream = await listener.AcceptConnectionAsync();

                TestUtility.Log("Client and Listener HybridStreams are connected!");

                byte[] sendBuffer = this.CreateBuffer(1024, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
                await clientStream.WriteAsync(sendBuffer, 0, sendBuffer.Length);

                TestUtility.Log($"clientStream wrote {sendBuffer.Length} bytes");

                byte[] readBuffer = new byte[sendBuffer.Length];
                await this.ReadCountBytesAsync(listenerStream, readBuffer, 0, readBuffer.Length, TimeSpan.FromSeconds(30));

                Assert.Equal(sendBuffer, readBuffer);

                TestUtility.Log("Calling clientStream.CloseAsync");
                var clientStreamCloseTask = clientStream.CloseAsync(new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token);
                TestUtility.Log("Reading from listenerStream");
                int bytesRead = await this.SafeReadAsync(listenerStream, readBuffer, 0, readBuffer.Length);

                TestUtility.Log($"listenerStream.Read returned {bytesRead} bytes");
                Assert.Equal(0, bytesRead);

                TestUtility.Log("Calling listenerStream.CloseAsync");
                var   listenerStreamCloseTask = listenerStream.CloseAsync(new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token);
                await listenerStreamCloseTask;
                TestUtility.Log("Calling listenerStream.CloseAsync completed");
                await clientStreamCloseTask;
                TestUtility.Log("Calling clientStream.CloseAsync completed");

                TestUtility.Log($"Closing {listener}");
                await listener.CloseAsync(TimeSpan.FromSeconds(10));

                listener = null;
            }
            finally
            {
                await this.SafeCloseAsync(listener);
            }
        }
예제 #26
0
        private static async Task RunAsync()
        {
            // Create the listener
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
            var listener      = new HybridConnectionListener(new Uri($"sb://{RelayNamespace}/{ConnectionName}"), tokenProvider);

            // Subscribe to the status events
            listener.Connecting += (o, e) => { Console.WriteLine("Connecting"); };
            listener.Offline    += (o, e) => { Console.WriteLine("Check service is offline"); };
            listener.Online     += (o, e) => { Console.WriteLine("Check service is online"); };

            // Create an array of credit status values
            var statuses = new List <string>
            {
                "Good",
                "Some issues",
                "Bad"
            };

            // Provide an HTTP request handler
            listener.RequestHandler = (context) =>
            {
                // Obtain the name from the request
                var reader        = new StreamReader(context.Request.InputStream);
                var requestedName = reader.ReadToEnd();
                Console.WriteLine("A request was received to check status for: " + requestedName);

                // Pick a status at random
                Random r     = new Random();
                var    index = r.Next(statuses.Count);

                // Formulate and send the response
                context.Response.StatusCode        = HttpStatusCode.OK;
                context.Response.StatusDescription = "Status check successful";

                using (var writer = new StreamWriter(context.Response.OutputStream))
                {
                    writer.WriteLine($"Status check for {requestedName}: {statuses[index]}");
                }

                // Close the context
                context.Response.Close();
            };

            // Open the listener
            await listener.OpenAsync();

            Console.WriteLine("Server listening");

            // Start a new thread that will continuously read the console.
            await Console.In.ReadLineAsync();

            // Close the listener after you exit the processing loop.
            await listener.CloseAsync();
        }
        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("Credit check service is offline"); };
            listener.Online     += (o, e) => { Console.WriteLine("Credit check service is online"); };

            // Create an array of credit status values
            List <string> creditStatuses = new List <string>();

            creditStatuses.Add("Good");
            creditStatuses.Add("Some issues");
            creditStatuses.Add("Bad");

            // Provide an HTTP request handler
            listener.RequestHandler = (context) =>
            {
                // Obtain the name from the request
                TextReader tr            = new StreamReader(context.Request.InputStream);
                String     requestedName = tr.ReadToEnd();
                Console.WriteLine("A request was received to check credit for: " + requestedName);

                // Pick a status at random
                Random r     = new Random();
                int    index = r.Next(creditStatuses.Count);

                // Formulate and send the response
                context.Response.StatusCode        = HttpStatusCode.OK;
                context.Response.StatusDescription = "Credit check successful";
                using (var sw = new StreamWriter(context.Response.OutputStream))
                {
                    sw.WriteLine("Credit check for {0}: {1}", requestedName, creditStatuses[index]);
                }

                // Close the context
                context.Response.Close();
            };

            // Open the listener
            await listener.OpenAsync();

            Console.WriteLine("Server listening");

            // Start a new thread that will continuously read the console.
            await Console.In.ReadLineAsync();

            // Close the listener after you exit the processing loop.
            await listener.CloseAsync();
        }
예제 #28
0
        public async Task CloseAsync(CancellationToken token)
        {
            _loopCancellationTokenSource?.Cancel();

            // Close the listener after we exit the processing loop
            if (_listener != null)
            {
                await _listener.CloseAsync(token);

                _listener = null;
            }
        }
        async Task LargeRequestEmptyResponse(EndpointTestType endpointTestType)
        {
            var cts = new CancellationTokenSource(TimeSpan.FromSeconds(60));
            HybridConnectionListener listener = this.GetHybridConnectionListener(endpointTestType);

            try
            {
                await listener.OpenAsync(cts.Token);

                string requestBody = null;
                listener.RequestHandler = async(context) =>
                {
                    TestUtility.Log("HybridConnectionListener.RequestHandler invoked with Request:");
                    TestUtility.Log($"{context.Request.HttpMethod} {context.Request.Url}");
                    context.Request.Headers.AllKeys.ToList().ForEach((k) => TestUtility.Log($"{k}: {context.Request.Headers[k]}"));
                    requestBody = StreamToString(context.Request.InputStream);
                    TestUtility.Log($"Body Length: {requestBody.Length}");
                    await context.Response.CloseAsync();
                };

                RelayConnectionStringBuilder connectionString = GetConnectionStringBuilder(endpointTestType);
                Uri endpointUri   = connectionString.Endpoint;
                Uri hybridHttpUri = new UriBuilder("https://", endpointUri.Host, endpointUri.Port, connectionString.EntityPath).Uri;

                using (var client = new HttpClient {
                    BaseAddress = hybridHttpUri
                })
                {
                    client.DefaultRequestHeaders.ExpectContinue = false;
                    var postRequest = new HttpRequestMessage();
                    await AddAuthorizationHeader(connectionString, postRequest, hybridHttpUri);

                    postRequest.Method = HttpMethod.Post;
                    var body = new string('y', 65 * 1024);
                    postRequest.Content = new StringContent(body);
                    LogRequest(postRequest, client, showBody: false);
                    using (HttpResponseMessage response = await client.SendAsync(postRequest, cts.Token))
                    {
                        LogResponse(response);
                        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                        Assert.Equal(0, response.Content.ReadAsStreamAsync().Result.Length);
                        Assert.Equal(body.Length, requestBody.Length);
                    }
                }

                await listener.CloseAsync(cts.Token);
            }
            finally
            {
                await SafeCloseAsync(listener);
            }
        }
        public async Task Start()
        {
            try
            {
                await _hybridConnectionListener.OpenAsync(_cts.Token);
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Unable to open hybrid connection listener for {_relayNamespace}/{_connectionName}");
                return;
            }


            await Task.Factory.StartNew(async() =>
            {
                _cts.Token.Register(() => _hybridConnectionListener.CloseAsync(CancellationToken.None));

                while (true)
                {
                    var client = await _hybridConnectionListener.AcceptConnectionAsync();
                    if (null == client)
                    {
                        await _hybridConnectionListener.CloseAsync(CancellationToken.None);
                        return;
                    }

                    var streamId = Guid.NewGuid();

                    lock (_syncRoot)
                    {
                        _hybridConnectionStreams.Add(streamId, client);
                    }

                    await OnNewClient(streamId, client, _cts.Token);
                }
            });
        }