Exemplo n.º 1
0
        [Ignore] //TODO #318
        public async Task WriteAfterCloseTest()
        {
            var websocket = new ClientWebSocket();

            // Set SubProtocol to AMQPWSB10
            websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Amqpwsb10);
            var uri = new Uri($"ws://{IotHubName}:{Port}{WebSocketConstants.UriSuffix}");
            await websocket.ConnectAsync(uri, CancellationToken.None).ConfigureAwait(false);

            using var clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);
            await clientWebSocketTransport.CloseAsync(s_thirtySeconds).ConfigureAwait(false);

            var args = new TransportAsyncCallbackArgs();

            args.SetBuffer(s_byteArray, 0, s_byteArray.Length);
            args.CompletedCallback = (TransportAsyncCallbackArgs args) =>
            {
                if (args.BytesTransfered != s_byteArray.Length)
                {
                    throw new InvalidOperationException("All the bytes sent were not transferred");
                }

                if (args.Exception != null)
                {
                    throw args.Exception;
                }
            };
            clientWebSocketTransport.WriteAsync(args);
        }
Exemplo n.º 2
0
        internal async Task <TransportBase> InitializeAsync(TimeSpan timeout)
        {
            Logging.Enter(this, timeout, nameof(InitializeAsync));

            TransportBase transport;

            switch (_amqpTransportSettings.GetTransportType())
            {
            case TransportType.Amqp_WebSocket_Only:
                transport = _clientWebSocketTransport = (ClientWebSocketTransport) await CreateClientWebSocketTransportAsync(timeout)
                                                        .ConfigureAwait(false);

                break;

            case TransportType.Amqp_Tcp_Only:
                var amqpTransportInitiator = new AmqpTransportInitiator(_amqpSettings, _tlsTransportSettings);
                transport = await amqpTransportInitiator.ConnectTaskAsync(timeout).ConfigureAwait(false);

                break;

            default:
                throw new InvalidOperationException("AmqpTransportSettings must specify WebSocketOnly or TcpOnly");
            }
            Logging.Exit(this, timeout, nameof(InitializeAsync));

            return(transport);
        }
Exemplo n.º 3
0
        private static RSocketClient CreateClient()
        {
            var factory   = new NullLoggerFactory();
            var transport = new ClientWebSocketTransport("ws://localhost:5000/api", factory.CreateLogger <WebSocketTransport>());

            return(new RSocketClient(transport));
        }
        public void ReadWriteAfterAbortTest()
        {
            var websocket = new ClientWebSocket();

            // Set SubProtocol to AMQPWSB10
            websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Amqpwsb10);
            Uri uri = new Uri("ws://" + IotHubName + ":" + Port + WebSocketConstants.UriSuffix);

            websocket.ConnectAsync(uri, CancellationToken.None).Wait(CancellationToken.None);
            clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);
            clientWebSocketTransport.Abort();

            try
            {
                TransportAsyncCallbackArgs args = new TransportAsyncCallbackArgs();
                args.SetBuffer(byteArray, 0, byteArray.Length);
                clientWebSocketTransport.WriteAsync(args);
                Assert.Fail("Did not throw object disposed exception");
            }
            catch (ObjectDisposedException)
            {
            }

            try
            {
                TransportAsyncCallbackArgs args = new TransportAsyncCallbackArgs();
                byte[] byteArray = new byte[10];
                args.SetBuffer(byteArray, 0, 10);
                clientWebSocketTransport.ReadAsync(args);
                Assert.Fail("Did not throw object disposed exception");
            }
            catch (ObjectDisposedException)
            {
            }
        }
Exemplo n.º 5
0
        public async Task AcceptTransportAsync_MultipleConnections_RetunsTransports()
        {
            // Arrange
            await Target.StartAsync(CancellationToken);

            var count            = Dummy.CreateRandomInt(100) + 1;
            var clientTransports = Enumerable.Range(0, count)
                                   .Select(async i =>
            {
                var clientTransport = new ClientWebSocketTransport(EnvelopeSerializer);
                await clientTransport.OpenAsync(ListenerUri, CancellationToken);
                return(clientTransport);
            })
                                   .ToList();

            // Act
            var acceptTasks = new List <Task <ITransport> >();

            while (count-- > 0)
            {
                acceptTasks.Add(
                    Task.Run(async() => await Target.AcceptTransportAsync(CancellationToken), CancellationToken));
            }

            await Task.WhenAll(acceptTasks);

            var actualTransports = acceptTasks.Select(t => t.Result).ToList();

            // Assert
            actualTransports.Count.ShouldBe(clientTransports.Count);
        }
        [Ignore] // TODO #581
        public async Task ReadWriteTest()
        {
            var websocket = new ClientWebSocket();

            // Set SubProtocol to AMQPWSB10
            websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Amqpwsb10);
            Uri uri = new Uri($"ws://{IotHubName}:{Port}{WebSocketConstants.UriSuffix}");
            await websocket.ConnectAsync(uri, CancellationToken.None).ConfigureAwait(false);

            s_clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);

            // Test Write API
            var args = new TransportAsyncCallbackArgs();

            args.CompletedCallback = s_onWriteOperationComplete;
            args.SetBuffer(s_byteArray, 0, s_byteArray.Length);
            s_clientWebSocketTransport.WriteAsync(args);

            // Test Read API
            args.CompletedCallback = s_onReadOperationComplete;
            if (s_clientWebSocketTransport.ReadAsync(args))
            {
                while (!s_isReadComplete)
                {
                    Thread.Sleep(s_oneSecond);
                }
            }

            // Once Read operation is complete, close websocket transport
            // Test Close API
            await s_clientWebSocketTransport.CloseAsync(s_thirtySeconds).ConfigureAwait(false);
        }
Exemplo n.º 7
0
        public async Task ReadWriteTest()
        {
            var websocket = new ClientWebSocket();

            // Set SubProtocol to AMQPWSB10
            websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Amqpwsb10);
            Uri uri = new Uri("ws://" + IotHubName + ":" + Port + WebSocketConstants.UriSuffix);
            await websocket.ConnectAsync(uri, CancellationToken.None).ConfigureAwait(false);

            clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);

            // Test Write API
            var args = new TransportAsyncCallbackArgs();

            args.CompletedCallback = onWriteOperationComplete;
            args.SetBuffer(byteArray, 0, byteArray.Length);
            clientWebSocketTransport.WriteAsync(args);

            // Test Read API
            args.CompletedCallback = onReadOperationComplete;
            if (clientWebSocketTransport.ReadAsync(args))
            {
                while (!readComplete)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                }
            }

            // Once Read operation is complete, close websocket transport
            // Test Close API
            await clientWebSocketTransport.CloseAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false);
        }
 public void ClientWebSocketTransportWriteWithoutConnectTest()
 {
     var websocket = new ClientWebSocket();
     var clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);
     var args = new TransportAsyncCallbackArgs();
     args.SetBuffer(byteArray, 0, byteArray.Length);
     clientWebSocketTransport.WriteAsync(args);
 }
Exemplo n.º 9
0
 public void SetUp()
 {
     ListenerUri        = new Uri("ws://localhost:8081");
     EnvelopeSerializer = new JsonNetSerializer();
     TraceWriter        = new Mock <ITraceWriter>();
     Listener           = new WebSocketTransportListener(ListenerUri, SslCertificate, EnvelopeSerializer, TraceWriter.Object);
     CancellationToken  = TimeSpan.FromSeconds(5).ToCancellationToken();
     Client             = new ClientWebSocketTransport(EnvelopeSerializer);
 }
Exemplo n.º 10
0
        public void ClientWebSocketTransportWriteWithoutConnectTest()
        {
            var websocket = new ClientWebSocket();
            var clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);
            var args = new TransportAsyncCallbackArgs();

            args.SetBuffer(byteArray, 0, byteArray.Length);
            clientWebSocketTransport.WriteAsync(args);
        }
Exemplo n.º 11
0
        public async Task StartAsync_ValidHostAndPort_ServerStarted()
        {
            // Act
            await Target.StartAsync();

            // Assert
            var clientTransport = new ClientWebSocketTransport(EnvelopeSerializer);
            await clientTransport.OpenAsync(ListenerUri, CancellationToken);
        }
        public void ClientWebSocketTransportReadTest()
        {
            var websocket = new ClientWebSocket();
            var clientWebSocketTransport    = new ClientWebSocketTransport(websocket, null, null);
            TransportAsyncCallbackArgs args = new TransportAsyncCallbackArgs();

            byte[] byteArray = new byte[10];
            args.SetBuffer(byteArray, 0, 10);
            clientWebSocketTransport.ReadAsync(args);
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            var loggerFactory = new NullLoggerFactory();
            var transport     = new ClientWebSocketTransport("ws://localhost:5000/api", loggerFactory.CreateLogger <WebSocketTransport>());
            var client        = new RSocketClient(transport);
            var dataProvider  = new ShopListApiDataProvider(client);
            //var invoker = new DefaultCallInvoker(null);
            var engine = new ShopMeEngine(dataProvider, null);

            RetrieveListAsync(client, engine).Wait();

            System.Console.WriteLine("Press key to close");
            System.Console.ReadLine();
        }
Exemplo n.º 14
0
        public async Task AcceptTransportAsync_NewConnection_RetunsTransport()
        {
            // Arrange
            await Target.StartAsync();

            var clientTransport = new ClientWebSocketTransport(EnvelopeSerializer);
            await clientTransport.OpenAsync(ListenerUri, CancellationToken);

            // Act
            var transport = await Target.AcceptTransportAsync(CancellationToken);

            // Assert
            transport.ShouldNotBeNull();
        }
Exemplo n.º 15
0
        public async Task WriteAfterAbortTest()
        {
            var websocket = new ClientWebSocket();

            // Set SubProtocol to AMQPWSB10
            websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Amqpwsb10);
            Uri uri = new Uri("ws://" + IotHubName + ":" + Port + WebSocketConstants.UriSuffix);
            await websocket.ConnectAsync(uri, CancellationToken.None).ConfigureAwait(false);

            clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);
            clientWebSocketTransport.Abort();
            var args = new TransportAsyncCallbackArgs();

            args.SetBuffer(byteArray, 0, byteArray.Length);
            clientWebSocketTransport.WriteAsync(args);
        }
Exemplo n.º 16
0
        public async Task ReadAfterAbortTest()
        {
            var websocket = new ClientWebSocket();

            // Set SubProtocol to AMQPWSB10
            websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Amqpwsb10);
            Uri uri = new Uri($"ws://{IotHubName}:{Port}{WebSocketConstants.UriSuffix}");
            await websocket.ConnectAsync(uri, CancellationToken.None).ConfigureAwait(false);

            using var clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);
            clientWebSocketTransport.Abort();
            var args      = new TransportAsyncCallbackArgs();
            var byteArray = new byte[10];

            args.SetBuffer(byteArray, 0, 10);
            clientWebSocketTransport.ReadAsync(args);
        }
        public async Task ClientWebSocketTransportReadWithoutConnectTest()
        {
            var websocket = new ClientWebSocket();
            var clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);
            var args = new TransportAsyncCallbackArgs();
            var byteArray = new byte[10];
            args.SetBuffer(byteArray, 0, 10);
            if (clientWebSocketTransport.ReadAsync(args))
            {
                while (!readComplete)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                }
            }

            await websocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
        }
        [Ignore] // TODO #581
        public async Task WriteAfterCloseTest()
        {
            var websocket = new ClientWebSocket();

            // Set SubProtocol to AMQPWSB10
            websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Amqpwsb10);
            var uri = new Uri($"ws://{IotHubName}:{Port}{WebSocketConstants.UriSuffix}");
            await websocket.ConnectAsync(uri, CancellationToken.None).ConfigureAwait(false);

            s_clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);
            await s_clientWebSocketTransport.CloseAsync(s_thirtySeconds).ConfigureAwait(false);

            var args = new TransportAsyncCallbackArgs();

            args.SetBuffer(s_byteArray, 0, s_byteArray.Length);
            args.CompletedCallback = s_onWriteOperationComplete;
            s_clientWebSocketTransport.WriteAsync(args);
        }
Exemplo n.º 19
0
        public async Task ClientWebSocketTransportReadWithoutConnectTest()
        {
            var websocket = new ClientWebSocket();
            var clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);
            var args      = new TransportAsyncCallbackArgs();
            var byteArray = new byte[10];

            args.SetBuffer(byteArray, 0, 10);
            if (clientWebSocketTransport.ReadAsync(args))
            {
                while (!readComplete)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                }
            }

            await websocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None).ConfigureAwait(false);
        }
        public async Task WriteAfterCloseTest()
        {
            var websocket = new ClientWebSocket();

            // Set SubProtocol to AMQPWSB10
            websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Amqpwsb10);
            var uri = new Uri("ws://" + IotHubName + ":" + Port + WebSocketConstants.UriSuffix);
            await websocket.ConnectAsync(uri, CancellationToken.None);

            clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);
            await clientWebSocketTransport.CloseAsync(TimeSpan.FromSeconds(30));

            var args = new TransportAsyncCallbackArgs();

            args.SetBuffer(byteArray, 0, byteArray.Length);
            args.CompletedCallback = onWriteOperationComplete;
            clientWebSocketTransport.WriteAsync(args);
        }
Exemplo n.º 21
0
        public async Task ClientWebSocketTransportReadWithoutConnectTest()
        {
            var  websocket = new ClientWebSocket();
            var  clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);
            var  args           = new TransportAsyncCallbackArgs();
            bool isReadComplete = false;

            args.CompletedCallback = (TransportAsyncCallbackArgs args) =>
            {
                if (args.Exception != null)
                {
                    throw args.Exception;
                }

                // Verify that data matches what was sent
                if (s_byteArray.Length != args.Count)
                {
                    throw new InvalidOperationException("Expected " + s_byteArray.Length + " bytes in response");
                }

                for (int i = 0; i < args.Count; i++)
                {
                    if (s_byteArray[i] != args.Buffer[i])
                    {
                        throw new InvalidOperationException("Response contents do not match what was sent");
                    }
                }

                isReadComplete = true;
            };
            var byteArray = new byte[10];

            args.SetBuffer(byteArray, 0, 10);
            if (clientWebSocketTransport.ReadAsync(args))
            {
                while (!isReadComplete)
                {
                    await Task.Delay(s_oneSecond);
                }
            }

            await websocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None).ConfigureAwait(false);
        }
Exemplo n.º 22
0
        public async Task StopAsync_ActiveListener_StopsListening()
        {
            // Arrange
            await Target.StartAsync(CancellationToken);

            // Act
            await Target.StopAsync(CancellationToken);

            // Assert
            try
            {
                var clientTransport = new ClientWebSocketTransport(EnvelopeSerializer);
                await clientTransport.OpenAsync(ListenerUri, CancellationToken);

                Assert.Fail("The listener is active");
            }
            catch (WebSocketException ex)
            {
                ex.NativeErrorCode.ShouldBe(10061);
            }
        }
        public void ReadWriteTest()
        {
            var websocket = new ClientWebSocket();

            // Set SubProtocol to AMQPWSB10
            websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Amqpwsb10);
            Uri uri = new Uri("ws://" + IotHubName + ":" + Port + WebSocketConstants.UriSuffix);

            websocket.ConnectAsync(uri, CancellationToken.None).Wait(CancellationToken.None);
            clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);

            // Test Write API
            TransportAsyncCallbackArgs args = new TransportAsyncCallbackArgs();

            args.CompletedCallback = onWriteOperationComplete;
            args.SetBuffer(byteArray, 0, byteArray.Length);
            clientWebSocketTransport.WriteAsync(args);

            // Test Read API
            args.CompletedCallback = onReadOperationComplete;
            clientWebSocketTransport.ReadAsync(args);
        }
Exemplo n.º 24
0
        [Ignore] //TODO #318
        public async Task ReadAfterCloseTest()
        {
            var websocket = new ClientWebSocket();

            // Set SubProtocol to AMQPWSB10
            websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Amqpwsb10);
            var uri = new Uri($"ws://{IotHubName}:{Port}{WebSocketConstants.UriSuffix}");
            await websocket.ConnectAsync(uri, CancellationToken.None).ConfigureAwait(false);

            using var clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);
            await clientWebSocketTransport.CloseAsync(s_thirtySeconds).ConfigureAwait(false);

            var args      = new TransportAsyncCallbackArgs();
            var byteArray = new byte[10];

            args.SetBuffer(byteArray, 0, 10);
            args.CompletedCallback = (TransportAsyncCallbackArgs args) =>
            {
                if (args.Exception != null)
                {
                    throw args.Exception;
                }

                // Verify that data matches what was sent
                if (s_byteArray.Length != args.Count)
                {
                    throw new InvalidOperationException("Expected " + s_byteArray.Length + " bytes in response");
                }

                for (int i = 0; i < args.Count; i++)
                {
                    if (s_byteArray[i] != args.Buffer[i])
                    {
                        throw new InvalidOperationException("Response contents do not match what was sent");
                    }
                }
            };
            clientWebSocketTransport.ReadAsync(args);
        }
Exemplo n.º 25
0
        async Task<AmqpSession> CreateSessionAsync(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            this.refreshTokenTimer.Cancel();

            var amqpSettings = this.CreateAmqpSettings();
            var tlsTransportSettings = this.CreateTlsTransportSettings();

            var amqpTransportInitiator = new AmqpTransportInitiator(amqpSettings, tlsTransportSettings);
            TransportBase transport;
            try
            {
                transport = await amqpTransportInitiator.ConnectTaskAsync(timeoutHelper.RemainingTime());
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                // Amqp transport over TCP failed. Retry Amqp transport over WebSocket
                if (timeoutHelper.RemainingTime() != TimeSpan.Zero)
                {
                    Uri websocketUri = new Uri(WebSocketConstants.Scheme + this.ConnectionString.HostName + ":" + WebSocketConstants.SecurePort + WebSocketConstants.UriSuffix);
                    var websocket = await this.CreateClientWebSocket(websocketUri, timeoutHelper.RemainingTime());
                    transport = new ClientWebSocketTransport(
                        websocket,
                        this.connectionString.IotHubName,
                        null,
                        null);
                }
                else
                {
                    throw;
                }
            }

            AmqpConnectionSettings amqpConnectionSettings = new AmqpConnectionSettings()
            {
                MaxFrameSize = AmqpConstants.DefaultMaxFrameSize,
                ContainerId = Guid.NewGuid().ToString("N"),
                HostName = this.connectionString.AmqpEndpoint.Host
            };

            var amqpConnection = new AmqpConnection(transport, amqpSettings, amqpConnectionSettings);
            await amqpConnection.OpenAsync(timeoutHelper.RemainingTime());

            var sessionSettings = new AmqpSessionSettings()
            {
                Properties = new Fields()
            };

            var amqpSession = amqpConnection.CreateSession(sessionSettings);
            await amqpSession.OpenAsync(timeoutHelper.RemainingTime());

            // This adds itself to amqpConnection.Extensions
            var cbsLink = new AmqpCbsLink(amqpConnection);
            await this.SendCbsTokenAsync(cbsLink, timeoutHelper.RemainingTime());
            return amqpSession;
        }
Exemplo n.º 26
0
 public void Dispose()
 {
     _clientWebSocketTransport?.Dispose();
     _clientWebSocketTransport = null;
 }
Exemplo n.º 27
0
        private async Task OpenTransportAsync()
        {
            await ExecuteAsync(async() =>
            {
                AddStatusMessage("Connecting...");

                var timeoutCancellationToken = _operationTimeout.ToCancellationToken();

                X509Certificate2 clientCertificate = null;

                if (!string.IsNullOrWhiteSpace(ClientCertificateThumbprint))
                {
                    ClientCertificateThumbprint = ClientCertificateThumbprint
                                                  .Replace(" ", "")
                                                  .Replace("‎", "");

                    var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

                    try
                    {
                        store.Open(OpenFlags.ReadOnly);

                        var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, ClientCertificateThumbprint, false);
                        if (certificates.Count > 0)
                        {
                            clientCertificate = certificates[0];

                            var identity = clientCertificate.GetIdentity();

                            if (identity != null)
                            {
                                var fromVariableViewModel = this.Variables.FirstOrDefault(v => v.Name.Equals("from", StringComparison.OrdinalIgnoreCase));

                                if (fromVariableViewModel == null)
                                {
                                    fromVariableViewModel = new VariableViewModel()
                                    {
                                        Name = "from"
                                    };

                                    this.Variables.Add(fromVariableViewModel);
                                }

                                fromVariableViewModel.Value = identity.ToString();
                            }
                        }
                        else
                        {
                            AddStatusMessage("The specified certificate was not found", true);
                        }
                    }
                    finally
                    {
                        store.Close();
                    }
                }

                if (_hostUri.Scheme == WebSocketTransportListener.UriSchemeWebSocket ||
                    _hostUri.Scheme == WebSocketTransportListener.UriSchemeWebSocketSecure)
                {
                    Transport = new ClientWebSocketTransport(
                        new JsonNetSerializer(),
                        this);
                }
                else
                {
                    TcpClient = new TcpClientAdapter(new TcpClient());
                    Transport = new TcpTransport(
                        TcpClient,
                        new JsonNetSerializer(),
                        _hostUri.Host,
                        clientCertificate,
                        traceWriter: this);
                }

                await Transport.OpenAsync(_hostUri, timeoutCancellationToken);

                _connectionCts = new CancellationTokenSource();

                var dispatcher = Dispatcher.CurrentDispatcher;

                _receiveTask = ReceiveAsync(
                    Transport,
                    (e) => ReceiveEnvelopeAsync(e, dispatcher),
                    _connectionCts.Token)
                               .WithCancellation(_connectionCts.Token)
                               .ContinueWith(t =>
                {
                    IsConnected = false;

                    if (t.Exception != null)
                    {
                        AddStatusMessage(string.Format("Disconnected with errors: {0}", t.Exception.InnerException.Message.RemoveCrLf()), true);
                    }
                    else
                    {
                        AddStatusMessage("Disconnected");
                    }
                }, TaskScheduler.FromCurrentSynchronizationContext());

                IsConnected  = true;
                CanSendAsRaw = true;

                AddStatusMessage("Connected");
            });
        }
        public async Task ReadWriteTest()
        {
            var websocket = new ClientWebSocket();
            // Set SubProtocol to AMQPWSB10
            websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Amqpwsb10);
            Uri uri = new Uri("ws://" + IotHubName + ":" + Port + WebSocketConstants.UriSuffix);
            await websocket.ConnectAsync(uri, CancellationToken.None);
            clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);

            // Test Write API
            var args = new TransportAsyncCallbackArgs();
            args.CompletedCallback = onWriteOperationComplete;
            args.SetBuffer(byteArray, 0, byteArray.Length);
            clientWebSocketTransport.WriteAsync(args);

            // Test Read API
            args.CompletedCallback = onReadOperationComplete;
            if (clientWebSocketTransport.ReadAsync(args))
            {
                while (!readComplete)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                }
            }

            // Once Read operation is complete, close websocket transport
            // Test Close API
            await clientWebSocketTransport.CloseAsync(TimeSpan.FromSeconds(30));
        }
 public async Task WriteAfterAbortTest()
 {
     var websocket = new ClientWebSocket();
     // Set SubProtocol to AMQPWSB10
     websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Amqpwsb10);
     Uri uri = new Uri("ws://" + IotHubName + ":" + Port + WebSocketConstants.UriSuffix);
     await websocket.ConnectAsync(uri, CancellationToken.None);
     clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);
     clientWebSocketTransport.Abort();
     var args = new TransportAsyncCallbackArgs();
     args.SetBuffer(byteArray, 0, byteArray.Length);
     clientWebSocketTransport.WriteAsync(args);
 }
        public async Task ReadAfterCloseTest()
        {
            var websocket = new ClientWebSocket();
            // Set SubProtocol to AMQPWSB10
            websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Amqpwsb10);
            var uri = new Uri("ws://" + IotHubName + ":" + Port + WebSocketConstants.UriSuffix);
            await websocket.ConnectAsync(uri, CancellationToken.None);
            clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);
            await clientWebSocketTransport.CloseAsync(TimeSpan.FromSeconds(30));

            var args = new TransportAsyncCallbackArgs();
            var byteArray = new byte[10];
            args.SetBuffer(byteArray, 0, 10);
            args.CompletedCallback = onReadOperationComplete;
            clientWebSocketTransport.ReadAsync(args);
        }
Exemplo n.º 31
0
        public async Task ReadWriteTest()
        {
            var websocket = new ClientWebSocket();

            // Set SubProtocol to AMQPWSB10
            websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Amqpwsb10);
            var uri = new Uri($"ws://{IotHubName}:{Port}{WebSocketConstants.UriSuffix}");
            await websocket.ConnectAsync(uri, CancellationToken.None).ConfigureAwait(false);

            using var clientWebSocketTransport = new ClientWebSocketTransport(websocket, null, null);

            // Test Write API
            var args = new TransportAsyncCallbackArgs();

            args.CompletedCallback = (TransportAsyncCallbackArgs args) =>
            {
                if (args.BytesTransfered != s_byteArray.Length)
                {
                    throw new InvalidOperationException("All the bytes sent were not transferred");
                }

                if (args.Exception != null)
                {
                    throw args.Exception;
                }
            };
            args.SetBuffer(s_byteArray, 0, s_byteArray.Length);
            clientWebSocketTransport.WriteAsync(args);

            // Test Read API
            bool isReadComplete = false;

            args.CompletedCallback = (TransportAsyncCallbackArgs args) =>
            {
                if (args.Exception != null)
                {
                    throw args.Exception;
                }

                // Verify that data matches what was sent
                if (s_byteArray.Length != args.Count)
                {
                    throw new InvalidOperationException("Expected " + s_byteArray.Length + " bytes in response");
                }

                for (int i = 0; i < args.Count; i++)
                {
                    if (s_byteArray[i] != args.Buffer[i])
                    {
                        throw new InvalidOperationException("Response contents do not match what was sent");
                    }
                }

                isReadComplete = true;
            };

            if (clientWebSocketTransport.ReadAsync(args))
            {
                while (!isReadComplete)
                {
                    await Task.Delay(s_oneSecond);
                }
            }

            // Once Read operation is complete, close websocket transport
            // Test Close API
            await clientWebSocketTransport.CloseAsync(s_thirtySeconds).ConfigureAwait(false);
        }