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

            websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Mqtt);
            Uri 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(
                MqttEncoder.Instance,
                new MqttDecoder(false, 256 * 1024),
                clientReadListener);
            var clientWorkerGroup = new MultithreadEventLoopGroup();
            await clientWorkerGroup.GetNext().RegisterAsync(clientChannel);

            await Task.WhenAll(RunMqttClientScenarioAsync(clientChannel, clientReadListener), RunMqttServerScenarioAsync(serverWebSocketChannel, serverListener));

            done = true;
        }
Exemplo n.º 2
0
        public async Task TestMap()
        {
            IEventLoopGroup group = new MultithreadEventLoopGroup();
            LocalAddress    addr  = new LocalAddress(ChannelPoolTestUtils.GetLocalAddrId());

            // Start server
            IChannel sc = await StartServerBootstrapAsync(group, addr);

            Bootstrap cb = new Bootstrap();

            cb.RemoteAddress(addr);
            cb.Group(group).Channel <LocalChannel>();
            var poolMap = new TestChannelPoolMap0(cb);

            IEventLoop loop = group.GetNext();

            Assert.True(poolMap.IsEmpty);
            Assert.Equal(0, poolMap.Count);

            SimpleChannelPool pool = poolMap.Get(loop);

            Assert.Equal(1, poolMap.Count);

            Assert.Same(pool, poolMap.Get(loop));
            Assert.True(poolMap.Remove(loop));
            Assert.False(poolMap.Remove(loop));

            Assert.Equal(0, poolMap.Count);

            await pool.AcquireAsync();

            poolMap.Close();

            await sc.CloseAsync();
        }
Exemplo n.º 3
0
        public async Task <IChannel> BindAsync(EndPoint localAddress)
        {
            var channel = this._channelFactory();

            //初始化handler
            _bossHandler(channel);
            channel.Pipeline.AddLast("ServerBootstrapAcceptor", new ServerBootstrapAcceptor(_workerGroup, _workerHandler));


            //注册事件循环
            await((IChannelUnsafe)channel).UnsafeRegisterAsync(_bossGroup.GetNext());

            await channel.BindAsync(localAddress);

            return(channel);
        }
Exemplo n.º 4
0
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var child = (IChannel)message;

            //在这里初始化 服务端接收的客户端连接
            InitChildChannel(child);

            //这个时候还没有事件循环呢
            ((IChannelUnsafe)child).UnsafeRegisterAsync(WorkerGroup.GetNext());

            //触发连接事件
            child.EventExecutor.Execute(() =>
            {
                child.Pipeline.FireChannelActive();
            });

            //交给下一个handler
            context.FireChannelRead(message);
        }
        static async Task RunWebSocketServer()
        {
            HttpListenerContext context = await listener.GetContextAsync();

            if (!context.Request.IsWebSocketRequest)
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                context.Response.Close();
            }

            HttpListenerWebSocketContext webSocketContext = await context.AcceptWebSocketAsync(WebSocketConstants.SubProtocols.Mqtt, 8 * 1024, TimeSpan.FromMinutes(5));

            serverListener         = new ReadListeningHandler();
            serverWebSocketChannel = new ServerWebSocketChannel(null, webSocketContext.WebSocket, context.Request.RemoteEndPoint);
            serverWebSocketChannel
            .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default)
            .Option(ChannelOption.AutoRead, true)
            .Option(ChannelOption.RcvbufAllocator, new AdaptiveRecvByteBufAllocator())
            .Option(ChannelOption.MessageSizeEstimator, DefaultMessageSizeEstimator.Default);
            serverWebSocketChannel.Pipeline.AddLast("server logger", new LoggingHandler("SERVER"));
            serverWebSocketChannel.Pipeline.AddLast(
                MqttEncoder.Instance,
                new MqttDecoder(true, 256 * 1024),
                serverListener);
            var workerGroup = new MultithreadEventLoopGroup();
            await workerGroup.GetNext().RegisterAsync(serverWebSocketChannel);

            while (true)
            {
                if (done)
                {
                    break;
                }

                await Task.Delay(TimeSpan.FromSeconds(2));
            }
        }
        Func <IPAddress, int, Task <IChannel> > CreateChannelFactory(IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings)
        {
#if WINDOWS_UWP
            return(async(address, port) =>
            {
                PlatformProvider.Platform = new UWPPlatform();

                var eventLoopGroup = new MultithreadEventLoopGroup();

                var streamSocket = new StreamSocket();
                await streamSocket.ConnectAsync(new HostName(iotHubConnectionString.HostName), port.ToString(), SocketProtectionLevel.PlainSocket);

                streamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
                await streamSocket.UpgradeToSslAsync(SocketProtectionLevel.Tls12, new HostName(iotHubConnectionString.HostName));

                var streamSocketChannel = new StreamSocketChannel(streamSocket);

                streamSocketChannel.Pipeline.AddLast(
                    MqttEncoder.Instance,
                    new MqttDecoder(false, MaxMessageSize),
                    this.mqttIotHubAdapterFactory.Create(this, iotHubConnectionString, settings));

                streamSocketChannel.Configuration.SetOption(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default);

                await eventLoopGroup.GetNext().RegisterAsync(streamSocketChannel);

                this.ScheduleCleanup(() =>
                {
                    EventLoopGroupPool.Release(this.eventLoopGroupKey);
                    return TaskConstants.Completed;
                });

                return streamSocketChannel;
            });
#else
            return((address, port) =>
            {
                IEventLoopGroup eventLoopGroup = EventLoopGroupPool.TakeOrAdd(this.eventLoopGroupKey);

                Func <Stream, SslStream> streamFactory = stream => new SslStream(stream, true, settings.RemoteCertificateValidationCallback);
                var clientTlsSettings = settings.ClientCertificate != null ?
                                        new ClientTlsSettings(iotHubConnectionString.HostName, new List <X509Certificate> {
                    settings.ClientCertificate
                }) :
                                        new ClientTlsSettings(iotHubConnectionString.HostName);
                Bootstrap bootstrap = new Bootstrap()
                                      .Group(eventLoopGroup)
                                      .Channel <TcpSocketChannel>()
                                      .Option(ChannelOption.TcpNodelay, true)
                                      .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default)
                                      .Handler(new ActionChannelInitializer <ISocketChannel>(ch =>
                {
                    var tlsHandler = new TlsHandler(streamFactory, clientTlsSettings);

                    ch.Pipeline
                    .AddLast(
                        tlsHandler,
                        MqttEncoder.Instance,
                        new MqttDecoder(false, MaxMessageSize),
                        this.mqttIotHubAdapterFactory.Create(this, iotHubConnectionString, settings));
                }));

                this.ScheduleCleanup(() =>
                {
                    EventLoopGroupPool.Release(this.eventLoopGroupKey);
                    return TaskConstants.Completed;
                });

                return bootstrap.ConnectAsync(address, port);
            });
#endif
        }