Exemplo n.º 1
0
        public async Task TestAcquireBoundQueue()
        {
            var addr = new LocalAddress(ChannelPoolTestUtils.GetLocalAddrId());
            Bootstrap cb = new Bootstrap().RemoteAddress(addr).Group(_group).Channel<LocalChannel>();

            ServerBootstrap sb = new ServerBootstrap()
                .Group(_group)
                .Channel<LocalServerChannel>()
                .ChildHandler(
                    new ActionChannelInitializer<LocalChannel>(
                        ch => ch.Pipeline.AddLast(new ChannelHandlerAdapter()))
                );

            // Start server
            IChannel sc = await sb.BindAsync(addr);
            var handler = new TestChannelPoolHandler();
            var pool = new FixedChannelPool(cb, handler, 1, 1);

            IChannel channel = await pool.AcquireAsync();
            var future = pool.AcquireAsync();
            Assert.False(future.IsCompleted);

            try
            {
                await Assert.ThrowsAsync<InvalidOperationException>(async () => await pool.AcquireAsync());
            }
            finally
            {
                await sc.CloseAsync();
                await channel.CloseAsync();
                pool.Close();
            }
        }
Exemplo n.º 2
0
        public async Task TestAcquireNewConnectionWhen()
        {
            var addr = new LocalAddress(ChannelPoolTestUtils.GetLocalAddrId());
            Bootstrap cb = new Bootstrap().RemoteAddress(addr).Group(_group).Channel<LocalChannel>();

            ServerBootstrap sb = new ServerBootstrap()
                .Group(_group)
                .Channel<LocalServerChannel>()
                .ChildHandler(
                    new ActionChannelInitializer<LocalChannel>(
                        ch => ch.Pipeline.AddLast(new ChannelHandlerAdapter()))
                );

            // Start server
            IChannel sc = await sb.BindAsync(addr);
            var handler = new TestChannelPoolHandler();
            var pool = new FixedChannelPool(cb, handler, 1);
            IChannel channel1 = await pool.AcquireAsync();
            await channel1.CloseAsync();
#pragma warning disable CS4014 // 由于此调用不会等待,因此在调用完成前将继续执行当前方法
            pool.ReleaseAsync(channel1);
#pragma warning restore CS4014 // 由于此调用不会等待,因此在调用完成前将继续执行当前方法

            IChannel channel2 = await pool.AcquireAsync();

            Assert.NotSame(channel1, channel2);
            await sc.CloseAsync();
            await channel2.CloseAsync();
            pool.Close();
        }
Exemplo n.º 3
0
        public async Task TestCloseAsync()
        {
            var addr = new LocalAddress(ChannelPoolTestUtils.GetLocalAddrId());
            Bootstrap cb = new Bootstrap().RemoteAddress(addr).Group(_group).Channel<LocalChannel>();

            ServerBootstrap sb = new ServerBootstrap()
                .Group(_group)
                .Channel<LocalServerChannel>()
                .ChildHandler(
                    new ActionChannelInitializer<LocalChannel>(
                        ch => ch.Pipeline.AddLast(new ChannelHandlerAdapter()))
                );

            // Start server
            IChannel sc = await sb.BindAsync(addr);

            var pool = new FixedChannelPool(cb, new TestChannelPoolHandler(), 2);
            await pool.AcquireAsync();
            await pool.AcquireAsync();

            var closePromise = sc.NewPromise();
            await pool.CloseAsync();

            Assert.Equal(0, pool.AcquiredChannelCount);
            await sc.CloseAsync(closePromise);

            Assert.True(closePromise.IsSuccess);
        }
Exemplo n.º 4
0
        public async Task TestAcquireNewConnection()
        {
            var addr = new LocalAddress(ChannelPoolTestUtils.GetLocalAddrId());
            Bootstrap cb = new Bootstrap().RemoteAddress(addr).Group(_group).Channel<LocalChannel>();

            ServerBootstrap sb = new ServerBootstrap()
                .Group(_group)
                .Channel<LocalServerChannel>()
                .ChildHandler(
                    new ActionChannelInitializer<LocalChannel>(
                        ch => ch.Pipeline.AddLast(new ChannelHandlerAdapter()))
                );

            // Start server
            IChannel sc = await sb.BindAsync(addr);
            var handler = new TestChannelPoolHandler();
            var pool = new FixedChannelPool(
                cb,
                handler,
                ChannelActiveHealthChecker.Instance,
                FixedChannelPool.AcquireTimeoutAction.New,
                TimeSpan.FromMilliseconds(500),
                1,
                int.MaxValue);

            IChannel channel = await pool.AcquireAsync();
            IChannel channel2 = await pool.AcquireAsync();
            Assert.NotSame(channel, channel2);
            await sc.CloseAsync();
            await channel.CloseAsync();
            await channel2.CloseAsync();
            pool.Close();
        }
        public async Task TestReleaseDifferentPool()
        {
            var       addr = new LocalAddress(LOCAL_ADDR_ID);
            Bootstrap cb   = new Bootstrap().RemoteAddress(addr).Group(this.group).Channel <LocalChannel>();

            ServerBootstrap sb = new ServerBootstrap()
                                 .Group(this.group)
                                 .Channel <LocalServerChannel>()
                                 .ChildHandler(
                new ActionChannelInitializer <LocalChannel>(
                    ch => ch.Pipeline.AddLast(new ChannelHandlerAdapter()))
                );

            // Start server
            IChannel sc = await sb.BindAsync(addr);

            var handler = new TestChannelPoolHandler();
            var pool    = new FixedChannelPool(cb, handler, 1, 1);
            var pool2   = new FixedChannelPool(cb, handler, 1, 1);

            IChannel channel = await pool.AcquireAsync();

            try
            {
                await Assert.ThrowsAsync <ArgumentException>(async() => await pool2.ReleaseAsync(channel));
            }
            finally
            {
                await sc.CloseAsync();

                await channel.CloseAsync();
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// TBD
 /// </summary>
 /// <returns>TBD</returns>
 public override int GetHashCode()
 {
     unchecked
     {
         return(((LocalAddress != null ? LocalAddress.GetHashCode() : 0) * 397) ^ (RemoteAddress != null ? RemoteAddress.GetHashCode() : 0));
     }
 }
        public async Task TestAcquireTimeout()
        {
            var       addr = new LocalAddress(LOCAL_ADDR_ID);
            Bootstrap cb   = new Bootstrap().RemoteAddress(addr).Group(this.group).Channel <LocalChannel>();

            ServerBootstrap sb = new ServerBootstrap()
                                 .Group(this.group)
                                 .Channel <LocalServerChannel>()
                                 .ChildHandler(
                new ActionChannelInitializer <LocalChannel>(
                    ch => ch.Pipeline.AddLast(new ChannelHandlerAdapter()))
                );

            // Start server
            IChannel sc = await sb.BindAsync(addr);

            var handler = new TestChannelPoolHandler();
            var pool    = new FixedChannelPool(cb, handler, ChannelActiveHealthChecker.Instance, FixedChannelPool.AcquireTimeoutAction.Fail, TimeSpan.FromMilliseconds(500), 1, int.MaxValue);

            IChannel channel = await pool.AcquireAsync();

            try
            {
                await Assert.ThrowsAsync <TimeoutException>(async() => await pool.AcquireAsync());
            }
            finally
            {
                await sc.CloseAsync();

                await channel.CloseAsync();
            }
        }
        public override int GetHashCode()
        {
            int hash = 1;

            if (localAddress_ != null)
            {
                hash ^= LocalAddress.GetHashCode();
            }
            if (metadata_ != null)
            {
                hash ^= Metadata.GetHashCode();
            }
            if (dataCase_ == DataOneofCase.LegacyDataMessage)
            {
                hash ^= LegacyDataMessage.GetHashCode();
            }
            if (dataCase_ == DataOneofCase.Content)
            {
                hash ^= Content.GetHashCode();
            }
            hash ^= (int)dataCase_;
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
        public async Task TestReleaseClosed()
        {
            var       addr = new LocalAddress(LOCAL_ADDR_ID);
            Bootstrap cb   = new Bootstrap().RemoteAddress(addr).Group(this.group).Channel <LocalChannel>();

            ServerBootstrap sb = new ServerBootstrap()
                                 .Group(this.group)
                                 .Channel <LocalServerChannel>()
                                 .ChildHandler(
                new ActionChannelInitializer <LocalChannel>(
                    ch => ch.Pipeline.AddLast(new ChannelHandlerAdapter()))
                );

            // Start server
            IChannel sc = await sb.BindAsync(addr);

            var      pool    = new FixedChannelPool(cb, new TestChannelPoolHandler(), 2);
            IChannel channel = await pool.AcquireAsync();

            await channel.CloseAsync();

            await pool.ReleaseAsync(channel);

            await sc.CloseAsync();
        }
Exemplo n.º 10
0
        public void Listen(int port, bool enableBroadcast = true, bool exclusiveAddressUse = false, bool ipV6 = false)
        {
            Close();
            _disposable = new CompositeDisposable();

            if (ipV6)
            {
                Client = new UdpClient(AddressFamily.InterNetworkV6);
            }
            else
            {
                Client = new UdpClient();
            }

            Client.EnableBroadcast     = enableBroadcast;
            Client.ExclusiveAddressUse = exclusiveAddressUse;
            if (!exclusiveAddressUse)
            {
                Client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            }
            Client.Client.Bind(new IPEndPoint(LocalAddress.Equals(IPAddress.None) ? (ipV6 ? IPAddress.IPv6Any : IPAddress.Any) : LocalAddress, port));
            _disposable.Add(
                Observable.Defer(() => Client.ReceiveAsync().ToObservable())
                .Repeat()
                .Subscribe(r => _received.OnNext(new UdpData(r.RemoteEndPoint, r.Buffer)))
                );

            IsMulticast = false;
        }
 public void MergeFrom(Connection other)
 {
     if (other == null)
     {
         return;
     }
     if (other.Id != 0UL)
     {
         Id = other.Id;
     }
     if (other.localAddress_ != null)
     {
         if (localAddress_ == null)
         {
             localAddress_ = new global::Envoy.Api.V2.Core.Address();
         }
         LocalAddress.MergeFrom(other.LocalAddress);
     }
     if (other.remoteAddress_ != null)
     {
         if (remoteAddress_ == null)
         {
             remoteAddress_ = new global::Envoy.Api.V2.Core.Address();
         }
         RemoteAddress.MergeFrom(other.RemoteAddress);
     }
     _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
 }
Exemplo n.º 12
0
        public async Task TestWriteFlushPingPong()
        {
            LocalAddress addr = new LocalAddress("testWriteFlushPingPong");

            ServerBootstrap sb = GetLocalServerBootstrap();
            await sb.BindAsync(addr);

            Bootstrap cb = GetLocalClientBootstrap();

            SetInterest(LoggingHandler.Event.WRITE, LoggingHandler.Event.FLUSH, LoggingHandler.Event.CLOSE, LoggingHandler.Event.EXCEPTION);

            var clientChannel = await cb.ConnectAsync(addr);

            clientChannel.Pipeline.AddLast(new ChannelOutboundHandlerAdapter0());

            clientChannel.WriteAndFlushAsync(CreateTestBuf(2000)).Ignore();
            await clientChannel.CloseAsync();

            AssertLog(
                "WRITE\n" +
                "FLUSH\n" +
                "WRITE\n" +
                "FLUSH\n" +
                "WRITE\n" +
                "FLUSH\n" +
                "WRITE\n" +
                "FLUSH\n" +
                "WRITE\n" +
                "FLUSH\n" +
                "WRITE\n" +
                "FLUSH\n" +
                "CLOSE\n");
        }
        public async Task TestReleaseAfterClosePool()
        {
            var       addr = new LocalAddress(LOCAL_ADDR_ID);
            Bootstrap cb   = new Bootstrap().RemoteAddress(addr).Group(this.group).Channel <LocalChannel>();

            ServerBootstrap sb = new ServerBootstrap()
                                 .Group(this.group)
                                 .Channel <LocalServerChannel>()
                                 .ChildHandler(
                new ActionChannelInitializer <LocalChannel>(
                    ch => ch.Pipeline.AddLast(new ChannelHandlerAdapter()))
                );

            // Start server
            IChannel sc = await sb.BindAsync(addr);

            var      pool    = new FixedChannelPool(cb, new TestChannelPoolHandler(), 2);
            IChannel channel = await pool.AcquireAsync();

            pool.Dispose();

            await group.GetNext().SubmitAsync(() => TaskEx.Completed);

            var e = await Assert.ThrowsAsync <InvalidOperationException>(async() => await pool.ReleaseAsync(channel));

            Assert.Same(FixedChannelPool.PoolClosedOnReleaseException, e);

            // Since the pool is closed, the Channel should have been closed as well.
            await channel.CloseCompletion;

            Assert.False(channel.Open, "Unexpected open channel");
            await sc.CloseAsync();
        }
Exemplo n.º 14
0
        public async Task TestFlushFailure()
        {
            LocalAddress addr = new LocalAddress("testFlushFailure");

            ServerBootstrap sb = GetLocalServerBootstrap();
            await sb.BindAsync(addr);

            Bootstrap cb = GetLocalClientBootstrap();

            SetInterest(LoggingHandler.Event.WRITE, LoggingHandler.Event.FLUSH, LoggingHandler.Event.CLOSE, LoggingHandler.Event.EXCEPTION);

            var clientChannel = await cb.ConnectAsync(addr);

            clientChannel.Pipeline.AddLast(new ChannelOutboundHandlerAdapter2());

            try
            {
                await clientChannel.WriteAndFlushAsync(CreateTestBuf(2000));

                Assert.False(true);
            }
            catch (Exception cce)
            {
                if (cce is AggregateException aggregateException)
                {
                    cce = aggregateException.InnerException;
                }
                // FIXME:  shouldn't this contain the "intentional failure" exception?
                Assert.IsType <ClosedChannelException>(cce);
            }

            await clientChannel.CloseCompletion;

            AssertLog("WRITE\nCLOSE\n");
        }
Exemplo n.º 15
0
        public async Task TestUnhealthyChannelIsOfferedWhenNoHealthCheckRequested()
        {
            var       group = new MultithreadEventLoopGroup();
            var       addr  = new LocalAddress(LOCAL_ADDR_ID);
            Bootstrap cb    = new Bootstrap().RemoteAddress(addr).Group(group).Channel <LocalChannel>();

            ServerBootstrap sb = new ServerBootstrap()
                                 .Group(group)
                                 .Channel <LocalServerChannel>()
                                 .ChildHandler(
                new ActionChannelInitializer <LocalChannel>(
                    ch => ch.Pipeline.AddLast(new ChannelHandlerAdapter()))
                );

            // Start server
            IChannel sc = await sb.BindAsync(addr);

            var      handler  = new CountingChannelPoolHandler();
            var      pool     = new SimpleChannelPool(cb, handler, ChannelActiveHealthChecker.Instance, false);
            IChannel channel1 = await pool.AcquireAsync();

            await channel1.CloseAsync();

            await pool.ReleaseAsync(channel1);

            IChannel channel2 = await pool.AcquireAsync();

            //verifying that in fact the channel2 is different that means is not pulled from the pool
            Assert.NotSame(channel1, channel2);
            await sc.CloseAsync();

            await channel2.CloseAsync();

            await group.ShutdownGracefullyAsync();
        }
Exemplo n.º 16
0
        public Http2MultiplexCodecBuilderTest(EventLoopGroupFixture fixture)
        {
            this.fixture = fixture;

            var          serverChannelLatch = new CountdownEvent(1);
            LocalAddress serverAddress      = new LocalAddress(this.GetType().Name);

            this.serverLastInboundHandler = new SharableLastInboundHandler();
            ServerBootstrap sb = new ServerBootstrap()
                                 .Channel <LocalServerChannel>()
                                 .Group(fixture.Group)
                                 .ChildHandler(new ActionChannelInitializer <IChannel>(ch =>
            {
                this.serverConnectedChannel = ch;
                ch.Pipeline.AddLast(new Http2MultiplexCodecBuilder(true, new ActionChannelInitializer <IChannel>(ch0 =>
                {
                    ch0.Pipeline.AddLast(new TestServerChannelHandler());
                    ch0.Pipeline.AddLast(this.serverLastInboundHandler);
                })).Build());
                serverChannelLatch.SafeSignal();
            }));

            this.serverChannel = sb.BindAsync(serverAddress).GetAwaiter().GetResult();
            Bootstrap cb = new Bootstrap()
                           .Channel <LocalChannel>()
                           .Group(fixture.Group)
                           .Handler(new Http2MultiplexCodecBuilder(false, new ActionChannelInitializer <IChannel>(ch =>
            {
                Assert.False(true, "Should not be called for outbound streams");
            })).Build());

            this.clientChannel = cb.ConnectAsync(serverAddress).GetAwaiter().GetResult();
            Assert.True(serverChannelLatch.Wait(TimeSpan.FromSeconds(5)));
        }
Exemplo n.º 17
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.º 18
0
        /// <summary>
        /// Starts accepting new connections.
        /// </summary>
        /// <param name="address">Listening interface default: 0.0.0.0 (all)</param>
        /// <param name="port">Listening port default: 2000</param>
        public new void StartAccept(string address = "0.0.0.0", int port = 2000)
        {
            base.StartAccept(address, port);

            // Update window title.
            ConsoleTitleBuilder.IP   = LocalAddress.ToString();
            ConsoleTitleBuilder.Port = port;
        }
        internal WidcommBluetoothRadio(WidcommBluetoothFactoryBase factory)
        {
            System.Threading.ThreadStart handleError = delegate { };
#if !NETCF
            // On my old iPAQ the radio info functions fail sometimes even though
            // the stack is working fine so we ignored the errors in the first
            // release.  On Win32 this is a problem when the stack is installed
            // but no radio is attached, so fail in that case.
            handleError = delegate {
                throw new PlatformNotSupportedException(
                          "Widcomm Bluetooth stack not supported (Radio).");
            };
#endif
            //
            Debug.Assert(factory != null);
            _factory = factory;
            var  tmp = BtIf;
            bool ret;
            ret = BtIf.GetLocalDeviceVersionInfo(ref m_dvi);
            Debug.Assert(ret, "GetLocalDeviceVersionInfo failed");
            if (!ret)
            {
                handleError();
                // Call handleError first so that one Win32 we don't get the Assert if there's no stack present.
                Debug.Assert(ret, "GetLocalDeviceVersionInfo failed");
                m_dvi = new DEV_VER_INFO(HciVersion.Unknown); // Reset to overwrite any garbage returned by GetLocalDeviceVersionInfo.
            }
            byte[] bdName = new byte[WidcommStructs.BD_NAME_LEN];
            ret = BtIf.GetLocalDeviceName(bdName);
            Debug.Assert(ret, "GetLocalDeviceName failed");
            if (ret)
            {
                m_name = WidcommUtils.BdNameToString(bdName);
            }
            else
            {
                bdName = null;
                handleError();
            }
            //
            // Did GetLocalDeviceVersionInfo get the address?  It doesn't work on
            // my iPAQ, but then again this way doesn't work either!
            if (LocalAddress == null || LocalAddress.ToInt64() == 0)
            {
                Utils.MiscUtils.Trace_WriteLine("GetLocalDeviceVersionInfo's bd_addr is empty, trying GetLocalDeviceInfoBdAddr...");
                if (m_dvi.bd_addr == null)
                {
                    m_dvi.bd_addr = new byte[WidcommStructs.BD_ADDR_LEN];
                }
                ret = BtIf.GetLocalDeviceInfoBdAddr(m_dvi.bd_addr);
                Debug.Assert(ret, "GetLocalDeviceInfoBdAddr failed");
                if (!ret)
                {
                    m_dvi.bd_addr = new byte[WidcommStructs.BD_ADDR_LEN];
                    handleError();
                }
            }
        }
        public void TestExceptionDuringConnect()
        {
            IEventLoopGroup group         = null;
            IChannel        serverChannel = null;
            IChannel        clientChannel = null;

            try
            {
                group = new DefaultEventLoopGroup(1);
                var addr      = new LocalAddress("a");
                var exception = new AtomicReference <Exception>();
                var sf        =
                    new ServerBootstrap().Channel <LocalServerChannel>().Group(group).ChildHandler(
                        new ActionChannelInitializer <IChannel>(ch =>
                {
                    ch.Pipeline.AddFirst(new HttpResponseEncoder());
                    var response = new DefaultFullHttpResponse(
                        HttpVersion.Http11,
                        HttpResponseStatus.BadGateway);
                    response.Headers.Add(AsciiString.Of("name"), "value");
                    response.Headers.Add(HttpHeaderNames.ContentLength, "0");
                    ch.WriteAndFlushAsync(response);
                }
                                                                )).BindAsync(addr);
                serverChannel = sf.Result;

                var cf = new Bootstrap().Channel <LocalChannel>().Group(group).Handler(
                    new ActionChannelInitializer <IChannel>(ch =>
                {
                    ch.Pipeline.AddFirst(new HttpProxyHandler(addr));
                    ch.Pipeline.AddLast(new ErrorCaptureHandler(exception));
                })).ConnectAsync(new DnsEndPoint("localhost", 1234));

                clientChannel = cf.Result;
                clientChannel.CloseAsync().Wait();

                Assert.True(exception.Value is HttpProxyConnectException);
                var actual = (HttpProxyConnectException)exception.Value;
                Assert.NotNull(actual.Headers);
                Assert.Equal("value", actual.Headers.GetAsString(AsciiString.Of("name")));
            }
            finally
            {
                if (clientChannel != null)
                {
                    clientChannel.CloseAsync();
                }
                if (serverChannel != null)
                {
                    serverChannel.CloseAsync();
                }
                if (group != null)
                {
                    @group.ShutdownGracefullyAsync().Wait();
                }
            }
        }
Exemplo n.º 21
0
 /// <summary>
 ///     Serves as the default hash function.
 /// </summary>
 /// <returns>
 ///     A hash code for the current object.
 /// </returns>
 public override int GetHashCode()
 {
     unchecked {
         if (string.IsNullOrEmpty(SheetName))
         {
             return(LocalAddress.GetHashCode());
         }
         return(SheetName.GetHashCode() ^ LocalAddress.GetHashCode());
     }
 }
Exemplo n.º 22
0
        private void SendLocalTopology(SignallingMessage message)
        {
            message.Operation                      = OperationType.LocalTopology;
            message.DestinationAddress             = LocalAddress.GetParentsAddress();
            message.DestinationControlPlaneElement =
                ControlPlaneElementType.RC;

            SendMessage(message);
            EndSession(message.SessionId);
        }
Exemplo n.º 23
0
 /// <summary>
 /// Overrode this to make sure that the <see cref="ReliableDeliverySupervisor"/> can correctly store
 /// <see cref="AckedReceiveBuffer{T}"/> data for each <see cref="Link"/> individually, since the HashCode
 /// is what Dictionary types use internally for equality checking by default.
 /// </summary>
 public override int GetHashCode()
 {
     unchecked
     {
         var hash = 17;
         hash = hash * 23 + (LocalAddress == null ? 0 : LocalAddress.GetHashCode());
         hash = hash * 23 + (RemoteAddress == null ? 0 : RemoteAddress.GetHashCode());
         return(hash);
     }
 }
Exemplo n.º 24
0
        public async Task TestAcquire()
        {
            var group = new MultithreadEventLoopGroup();
            var addr  = new LocalAddress(ChannelPoolTestUtils.GetLocalAddrId());
            var cb    = new Bootstrap().RemoteAddress(addr).Group(group).Channel <LocalChannel>();

            var sb = new ServerBootstrap()
                     .Group(group)
                     .Channel <LocalServerChannel>()
                     .ChildHandler(
                new ActionChannelInitializer <LocalChannel>(
                    ch => ch.Pipeline.AddLast(new ChannelHandlerAdapter()))
                );

            // Start server
            IChannel sc = await sb.BindAsync(addr);

            var handler = new CountingChannelPoolHandler();

            var pool = new SimpleChannelPool(cb, handler);

            IChannel channel = await pool.AcquireAsync();

            await pool.ReleaseAsync(channel);

            IChannel channel2 = await pool.AcquireAsync();

            Assert.Same(channel, channel2);
            Assert.Equal(1, handler.ChannelCount);
            await pool.ReleaseAsync(channel2);

            // Should fail on multiple release calls.
            await Assert.ThrowsAsync <ArgumentException>(async() => await pool.ReleaseAsync(channel2));

            Assert.False(channel.Active);
            try
            {
                await pool.ReleaseAsync(channel2);

                Assert.True(false, "release should fail");
            }
            catch (ArgumentException)
            {
                // expected
                Assert.False(channel.Active);
            }

            Assert.Equal(1, handler.AcquiredCount);
            Assert.Equal(2, handler.ReleasedCount);

            await sc.CloseAsync();

            pool.Close();
            await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5));
        }
        private void SendLocalTopology(Link link)
        {
            var message = new SignallingMessage {
                Operation                      = OperationType.LocalTopology,
                DestinationAddress             = LocalAddress.GetParentsAddress(),
                DestinationControlPlaneElement = ControlPlaneElementType.RC,
                Payload = link
            };

            SendMessage(message);
        }
Exemplo n.º 26
0
        public String ChangeTag(String src)
        {
            var tagList = new[] { "$h", "$v", "$p", "$d", "$a", "$s" };

            foreach (var tag in tagList)
            {
                while (true)
                {
                    var index = src.IndexOf(tag);
                    if (index == -1)
                    {
                        break;
                    }
                    var tmp1 = src.Substring(0, index);
                    var tmp2 = "";
                    switch (tag)
                    {
                    case "$h":
                        var serverName = ServerName;
                        tmp2 = serverName == "" ? "localhost" : serverName;
                        break;

                    case "$v":
                        tmp2 = Ver.Version();
                        break;

                    case "$p":
                        tmp2 = Define.ApplicationName();
                        break;

                    case "$d":
                        tmp2 = Define.Date();
                        break;

                    case "$a":
                        var localAddress = LocalAddress.GetInstance();
                        tmp2 = localAddress.RemoteStr();
                        //tmp2 = Define.ServerAddress();
                        break;

                    case "$s":
                        tmp2 = ServerName;
                        break;

                    default:
                        Util.RuntimeException(string.Format("undefind tag = {0}", tag));
                        break;
                    }
                    var tmp3 = src.Substring(index + 2);
                    src = tmp1 + tmp2 + tmp3;
                }
            }
            return(src);
        }
Exemplo n.º 27
0
        public async Task TestChannelInitializerEventExecutor()
        {
            AtomicInteger invokeCount            = new AtomicInteger();
            AtomicInteger completeCount          = new AtomicInteger();
            AtomicReference <Exception> errorRef = new AtomicReference <Exception>();
            LocalAddress addr = new LocalAddress("test");

            IEventExecutor executor = new DefaultEventLoop();

            CountdownEvent  latch           = new CountdownEvent(1);
            ServerBootstrap serverBootstrap = new ServerBootstrap()
                                              .Channel <LocalServerChannel>()
                                              .Group(_group)
                                              .LocalAddress(addr)
                                              .ChildHandler(new ActionChannelInitializer <IChannel>(ch =>
            {
                ch.Pipeline.AddLast(executor, new ChannelInitializer1(invokeCount, completeCount, errorRef, latch));
            }));

            IChannel server = await serverBootstrap.BindAsync();

            Bootstrap clientBootstrap = new Bootstrap()
                                        .Channel <LocalChannel>()
                                        .Group(_group)
                                        .RemoteAddress(addr)
                                        .Handler(new ChannelHandlerAdapter());

            IChannel client = await clientBootstrap.ConnectAsync();

            await client.WriteAndFlushAsync("Hello World");

            await client.CloseAsync();

            await server.CloseAsync();

            await client.CloseCompletion;
            await server.CloseCompletion;

            // Wait until the handler is removed from the pipeline and so no more events are handled by it.
            Assert.True(latch.Wait(TimeSpan.FromMinutes(1)));

            Assert.Equal(1, invokeCount.Value);
            Assert.Equal(invokeCount.Value, completeCount.Value);

            Exception cause = errorRef.Value;

            if (cause != null)
            {
                throw cause;
            }

            await executor.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5));
        }
Exemplo n.º 28
0
        private static async Task TestParentHandler0(bool channelInitializer)
        {
            LocalAddress   addr      = new LocalAddress(Guid.NewGuid().ToString());
            CountdownEvent readLatch = new CountdownEvent(1);
            CountdownEvent initLatch = new CountdownEvent(1);

            IChannelHandler handler = new TestHandler(readLatch, initLatch);

            IEventLoopGroup group = new DefaultEventLoopGroup(1);
            IChannel        sch   = null;
            IChannel        cch   = null;

            try
            {
                ServerBootstrap sb = new ServerBootstrap();
                sb.Channel <LocalServerChannel>()
                .Group(group)
                .ChildHandler(new ChannelHandlerAdapter());
                if (channelInitializer)
                {
                    sb.Handler(new ActionChannelInitializer <IChannel>(ch => ch.Pipeline.AddLast(handler)));
                }
                else
                {
                    sb.Handler(handler);
                }

                Bootstrap cb = new Bootstrap();
                cb.Group(group)
                .Channel <LocalChannel>()
                .Handler(new ChannelHandlerAdapter());

                sch = await sb.BindAsync(addr);

                cch = await cb.ConnectAsync(addr);

                initLatch.Wait();
                readLatch.Wait();
            }
            finally
            {
                if (sch != null)
                {
                    await sch.CloseAsync();
                }
                if (cch != null)
                {
                    await cch.CloseAsync();
                }
                await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5));
            }
        }
Exemplo n.º 29
0
        public void RemoteStrで取得したテキストで改めてLocalAddressを生成して同じかどうかを確認()
        {
            //setUp
            var localAddress = LocalAddress.GetInstance();
            var expected     = localAddress.RemoteStr();

            //exercise
            var sut    = new LocalAddress(expected);
            var actual = sut.RemoteStr();

            //verify
            Assert.That(actual, Is.EqualTo(expected));
        }
Exemplo n.º 30
0
        public LocalTransportThreadModelTest()
        {
            // Configure a test server
            _group = new DefaultEventLoopGroup();
            ServerBootstrap sb = new ServerBootstrap();

            sb.Group(_group)
            .Channel <LocalServerChannel>()
            .ChildHandler(new ActionChannelInitializer <LocalChannel>(ch =>
            {
                ch.Pipeline.AddLast(new ChannelInboundHandlerAdapter0());
            }));
            _localAddr = (LocalAddress)sb.BindAsync(LocalAddress.Any).GetAwaiter().GetResult().LocalAddress;
        }