public async Task ClientWebSocketChannelWriteAfterCloseTest()
        {
            var websocket = new ClientWebSocket();

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

            clientWebSocketChannel = new ClientWebSocketChannel(null, websocket);

            var threadLoop = new SingleThreadEventLoop("MQTTExecutionThread", TimeSpan.FromSeconds(1));
            await threadLoop.RegisterAsync(clientWebSocketChannel);

            await clientWebSocketChannel.CloseAsync();

            // Test Write API
            try
            {
                await clientWebSocketChannel.WriteAndFlushAsync(Unpooled.Buffer());

                Assert.Fail("Should have thrown ClosedChannelException");
            }
            catch (AggregateException e)
            {
                var innerException = e.InnerException as ClosedChannelException;
                Assert.IsNotNull(innerException);
            }

            done = true;
        }
示例#2
0
        public async Task StartWithExistingSocket(StreamSocket socket)
        {
            try
            {
                Debug.WriteLine($"{nameof(PushClient)}: Starting with existing socket.");
                Socket = socket;
                if (_loopGroup != null)
                {
                    await Shutdown().ConfigureAwait(false);
                }
                _loopGroup = new SingleThreadEventLoop();

                var streamSocketChannel = new StreamSocketChannel(Socket);
                streamSocketChannel.Pipeline.AddLast(new FbnsPacketEncoder(), new FbnsPacketDecoder(), this);

                await _loopGroup.RegisterAsync(streamSocketChannel).ConfigureAwait(false);
                await SendPing().ConfigureAwait(false);

                await _context.Executor.Schedule(KeepAliveLoop, TimeSpan.FromSeconds(KEEP_ALIVE - 60));
            }
            catch (TaskCanceledException)
            {
                // pass
            }
            catch (Exception e)
            {
#if !DEBUG
                Crashes.TrackError(e);
#endif
                await Shutdown().ConfigureAwait(false);
            }
        }
        public async Task ClientWebSocketChannelReadWithoutConnectTest()
        {
            var websocket = new ClientWebSocket();

            clientWebSocketChannel = new ClientWebSocketChannel(null, websocket);
            var threadLoop = new SingleThreadEventLoop("MQTTExecutionThread", TimeSpan.FromSeconds(1));
            await threadLoop.RegisterAsync(clientWebSocketChannel);

            clientWebSocketChannel.Read();
        }
        public async Task ClientWebSocketChannelWriteWithoutConnectTest()
        {
            var websocket = new ClientWebSocket();

            clientWebSocketChannel = new ClientWebSocketChannel(null, websocket);
            var threadLoop = new SingleThreadEventLoop("MQTTExecutionThread", TimeSpan.FromSeconds(1));
            await threadLoop.RegisterAsync(clientWebSocketChannel).ConfigureAwait(false);

            await clientWebSocketChannel.WriteAndFlushAsync(new ConnectPacket()).ConfigureAwait(false);
        }
        public async Task CanCloseTheChannel()
        {
            var webSocket = Mock.Of <WebSocket>(ws => ws.State == WebSocketState.Open);
            var channel   = new ServerWebSocketChannel(webSocket, Mock.Of <EndPoint>());
            var loop      = new SingleThreadEventLoop();
            await loop.RegisterAsync(channel);

            await channel.CloseAsync();

            Assert.False(channel.Active);
            Mock.Get(webSocket).Verify(
                ws => ws.CloseAsync(WebSocketCloseStatus.NormalClosure, It.IsAny <string>(), It.IsAny <CancellationToken>()));
        }
        public async Task DoesNotCloseAnAlreadyClosedWebSocket()
        {
            var webSocket = Mock.Of <WebSocket>(ws => ws.State == WebSocketState.Open);
            var channel   = new ServerWebSocketChannel(webSocket, Mock.Of <EndPoint>());
            var loop      = new SingleThreadEventLoop();
            await loop.RegisterAsync(channel);

            Mock <WebSocket> wsMock = Mock.Get(webSocket);

            wsMock.Setup(ws => ws.State).Returns(WebSocketState.Closed);
            wsMock.Setup(ws => ws.CloseAsync(It.IsAny <WebSocketCloseStatus>(), It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Throws(new Exception("WebSocket.CloseAsync should not be called"));

            await channel.CloseAsync();
        }
        public async Task ClientWebSocketChannelReadAfterCloseTest()
        {
            var websocket = new ClientWebSocket();

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

            var clientReadListener = new ReadListeningHandler();
            var clientChannel      = new ClientWebSocketChannel(null, websocket);

            clientChannel
            .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default)
            .Option(ChannelOption.AutoRead, true)
            .Option(ChannelOption.RcvbufAllocator, new AdaptiveRecvByteBufAllocator())
            .Option(ChannelOption.MessageSizeEstimator, DefaultMessageSizeEstimator.Default);

            clientChannel.Pipeline.AddLast(
                clientReadListener);
            var threadLoop = new SingleThreadEventLoop("MQTTExecutionThread", TimeSpan.FromSeconds(1));
            await threadLoop.RegisterAsync(clientChannel);

            await clientChannel.CloseAsync();

            // Test Read API
            try
            {
                await clientReadListener.ReceiveAsync(DefaultTimeout);

                Assert.Fail("Should have thrown InvalidOperationException");
            }
            catch (InvalidOperationException e)
            {
                Assert.IsTrue(e.Message.Contains("Channel is closed"));
            }

            done = true;
        }
示例#8
0
        public async Task StartFresh()
        {
            try
            {
                Debug.WriteLine($"{nameof(PushClient)}: Starting fresh.");
                if (_loopGroup != null)
                {
                    await Shutdown();
                }
                _loopGroup = new SingleThreadEventLoop();

                var connectPacket = new FbnsConnectPacket
                {
                    Payload = await PayloadProcessor.BuildPayload(ConnectionData)
                };

                Socket = new StreamSocket();
                Socket.Control.KeepAlive = true;
                Socket.Control.NoDelay   = true;
                if (await RequestBackgroundAccess())
                {
                    try
                    {
                        Socket.EnableTransferOwnership(_socketActivityTask.TaskId, SocketActivityConnectedStandbyAction.Wake);
                    }
                    catch (Exception connectedStandby)
                    {
                        Debug.WriteLine(connectedStandby);
                        Debug.WriteLine($"{nameof(PushClient)}: Connected standby not available.");
                        try
                        {
                            Socket.EnableTransferOwnership(_socketActivityTask.TaskId, SocketActivityConnectedStandbyAction.DoNotWake);
                        }
                        catch (Exception e)
                        {
#if !DEBUG
                            Crashes.TrackError(e);
#endif
                            Debug.WriteLine(e);
                            Debug.WriteLine($"{nameof(PushClient)}: Failed to transfer socket completely!");
                            await Shutdown().ConfigureAwait(false);

                            return;
                        }
                    }
                }

                await Socket.ConnectAsync(new HostName(HOST_NAME), "443", SocketProtectionLevel.Tls12);

                var streamSocketChannel = new StreamSocketChannel(Socket);
                streamSocketChannel.Pipeline.AddLast(new FbnsPacketEncoder(), new FbnsPacketDecoder(), this);

                await _loopGroup.RegisterAsync(streamSocketChannel).ConfigureAwait(false);

                await streamSocketChannel.WriteAndFlushAsync(connectPacket).ConfigureAwait(false);
            }
            catch (Exception e)
            {
#if !DEBUG
                Crashes.TrackError(e);
#endif
                await Shutdown().ConfigureAwait(false);
            }
        }