示例#1
0
        public void BindAsync()
        {
            var bootstrap = new ServerBootstrap();

            bootstrap.Group(this.BossGroup, this.WorkerGroup)
            .Channel <TcpServerSocketChannel>()
            .Handler(new LoggingHandler(LogLevel.INFO));
            if (Config.Type == LazynetSocketType.TcpSocket)
            {
                bootstrap.ChildHandler(new LazynetTSChannelInitializer(this));
            }
            else if (Config.Type == LazynetSocketType.Websocket)
            {
                if (string.IsNullOrEmpty(this.Config.WSPath))
                {
                    throw new Exception("使用websocket时[path]参数必填");
                }
                bootstrap.ChildHandler(new LazynetWSChannelInitializer(this));
            }
            else
            {
                throw new Exception("没有其它类型的socket");
            }
            this.BindResult = bootstrap.BindAsync(this.Config.Port);
        }
示例#2
0
        void SimpleEcho0(ServerBootstrap sb, Bootstrap cb, bool additionalExecutor, bool autoRead)
        {
            var sh = new EchoHandler(autoRead, this.data, this.output);
            var ch = new EchoHandler(autoRead, this.data, this.output);

            if (additionalExecutor)
            {
                sb.ChildHandler(new ActionChannelInitializer <TcpChannel>(channel =>
                {
                    channel.Pipeline.AddLast(this.group, sh);
                }));
                cb.Handler(new ActionChannelInitializer <TcpChannel>(channel =>
                {
                    channel.Pipeline.AddLast(this.group, ch);
                }));
            }
            else
            {
                sb.ChildHandler(sh);
                sb.Handler(new ErrorOutputHandler(this.output));
                cb.Handler(ch);
            }
            sb.ChildOption(ChannelOption.AutoRead, autoRead);
            cb.Option(ChannelOption.AutoRead, autoRead);

            // start server
            Task <IChannel> task = sb.BindAsync(LoopbackAnyPort);

            Assert.True(task.Wait(DefaultTimeout), "Server bind timed out");
            this.serverChannel = task.Result;
            Assert.NotNull(this.serverChannel.LocalAddress);
            var endPoint = (IPEndPoint)this.serverChannel.LocalAddress;

            // connect to server
            task = cb.ConnectAsync(endPoint);
            Assert.True(task.Wait(DefaultTimeout), "Connect to server timed out");
            this.clientChannel = task.Result;
            Assert.NotNull(this.clientChannel.LocalAddress);

            for (int i = 0; i < this.data.Length;)
            {
                int         length = Math.Min(this.random.Next(1024 * 64), this.data.Length - i);
                IByteBuffer buf    = Unpooled.WrappedBuffer(this.data, i, length);
                this.clientChannel.WriteAndFlushAsync(buf);
                i += length;
            }

            Assert.True(Task.WhenAll(ch.Completion, sh.Completion).Wait(DefaultTimeout), "Echo read/write timed out");
        }
示例#3
0
        static async Task RunServerAsync()
        {
            IEventLoopGroup eventLoop = new MultithreadEventLoopGroup();

            try
            {
                ServerBootstrap bootstrap = new ServerBootstrap();
                bootstrap.Group(eventLoop);
                bootstrap.Channel <TcpServerSocketChannel>();
                bootstrap.ChildHandler(new ActionChannelInitializer <IChannel>(chl =>
                {
                    chl.Pipeline.AddLast(new ServerTestHandler());
                }));

                IChannel channel = await bootstrap.BindAsync(3000);

                Console.WriteLine("服务器已启动.........");

                Console.ReadLine();//阻塞线程

                await channel.CloseAsync();
            }
            catch (Exception ex)
            { }
            finally
            {
                await eventLoop.ShutdownGracefullyAsync();
            }
        }
示例#4
0
        private void Initialize()
        {
            if (Initializer == null)
            {
                Out.QuickLog("Abstract server failed to start on Port " + Port + " due to the server's initializer being NULL");
                return;
            }

            _bootstrap.Group(_bossEventLoopGroup,
                             _workerEventLoopGroup);

            // Set Channel Type to Tcp.
            _bootstrap.Channel <TcpServerSocketChannel>();

            // Set Server Options
            _bootstrap.Option(ChannelOption.SoLinger, 0);
            _bootstrap.Option(ChannelOption.SoBacklog, Backlog);

            _bootstrap.ChildHandler(Initializer);

            _bootstrap.ChildOption(ChannelOption.SoLinger, 0);
            _bootstrap.ChildOption(ChannelOption.SoKeepalive, true);
            _bootstrap.ChildOption(ChannelOption.TcpNodelay, true);
            _bootstrap.ChildOption(ChannelOption.SoReuseaddr, true);
        }
示例#5
0
 protected override Task StartAsync(CancellationToken cancellationToken)
 {
     try
     {
         var dispatcher = new DispatcherEventLoopGroup();
         bossGroup   = dispatcher;
         workerGroup = new WorkerEventLoopGroup(dispatcher);
         var bootstrap = new ServerBootstrap();
         bootstrap.Group(bossGroup, workerGroup);
         bootstrap.Channel <TcpServerChannel>();
         bootstrap
         //.Handler(new LoggingHandler("SRV-LSTN"))
         .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
         {
             InitChannel(channel);
         }))
         .Option(ChannelOption.SoBacklog, 1048576);
         if (nettyOptions.Host == "")
         {
             boundChannel = bootstrap.BindAsync(nettyOptions.Port).Result;
         }
         else
         {
             boundChannel = bootstrap.BindAsync(nettyOptions.Host, nettyOptions.Port).Result;
         }
     }
     catch (Exception ex)
     {
     }
     return(Task.CompletedTask);
 }
示例#6
0
        void ReadPendingIsResetAfterEachRead0(ServerBootstrap sb, Bootstrap cb)
        {
            var serverInitializer = new MyInitializer();

            sb.Option(ChannelOption.SoBacklog, 1024);
            sb.ChildHandler(serverInitializer);

            // start server
            Task <IChannel> task = sb.BindAsync(LoopbackAnyPort);

            Assert.True(task.Wait(DefaultTimeout), "Server bind timed out");
            this.serverChannel = task.Result;
            Assert.NotNull(this.serverChannel.LocalAddress);
            var endPoint = (IPEndPoint)this.serverChannel.LocalAddress;

            cb.Handler(new MyInitializer());
            // connect to server
            task = cb.ConnectAsync(endPoint);
            Assert.True(task.Wait(DefaultTimeout), "Connect to server timed out");
            this.clientChannel = task.Result;
            Assert.NotNull(this.clientChannel.LocalAddress);

            Task writeTask = this.clientChannel.WriteAndFlushAsync(Unpooled.WrappedBuffer(new byte[1024]));

            Assert.True(writeTask.Wait(DefaultTimeout), "Write task timed out");

            ExceptionHandler exceptionHandler = serverInitializer.ErrorHandler;

            Assert.True(exceptionHandler.Inactive.Wait(DefaultTimeout), "Handler inactive timed out");
            Assert.Equal(1, exceptionHandler.Count);
        }
示例#7
0
        public void TestAsyncResolutionFailure()
        {
            Bootstrap bootstrapA = new Bootstrap();

            bootstrapA.Group(_groupA);
            bootstrapA.Channel <LocalChannel>();
            bootstrapA.Resolver(new TestAddressResolverGroup(false));
            bootstrapA.Handler(_dummyHandler);

            ServerBootstrap bootstrapB = new ServerBootstrap();

            bootstrapB.Group(_groupB);
            bootstrapB.Channel <LocalServerChannel>();
            bootstrapB.ChildHandler(_dummyHandler);
            var localAddress = bootstrapB.BindAsync(LocalAddress.Any).GetAwaiter().GetResult().LocalAddress;

            // Connect to the server using the asynchronous resolver.
            var connectFuture = bootstrapA.ConnectAsync(localAddress);

            // Should fail with the UnknownHostException.
            Assert.True(TaskUtil.WaitAsync(connectFuture, TimeSpan.FromSeconds(10)).GetAwaiter().GetResult());
            Assert.False(connectFuture.IsSuccess());
            Assert.IsType <System.Net.Sockets.SocketException>(connectFuture.Exception.InnerException);
            //Assert.False(connectFuture.Channel().isOpen());
        }
示例#8
0
        private async Task TestNoRstIfSoLingerOnClose0(ServerBootstrap sb, Bootstrap cb)
        {
            AtomicReference <IChannel>  serverChannelRef = new AtomicReference <IChannel>();
            AtomicReference <Exception> throwableRef     = new AtomicReference <Exception>();
            CountdownEvent latch  = new CountdownEvent(1);
            CountdownEvent latch2 = new CountdownEvent(1);

            sb.ChildHandler(new ActionChannelInitializer <IChannel>(ch =>
            {
                serverChannelRef.CompareAndSet(null, ch);
                latch.SafeSignal();
            }));
            cb.Handler(new ActionChannelInitializer <IChannel>(ch =>
            {
                ch.Pipeline.AddLast(new ChannelInboundHandlerAdapter0(throwableRef, latch2));
            }));
            IChannel sc = await sb.BindAsync();

            await cb.ConnectAsync(sc.LocalAddress);

            // Wait for the server to get setup.
            latch.Wait();

            // The server has SO_LINGER=0 and so it must send a RST when close is called.
            serverChannelRef.Value.CloseAsync().Ignore();

            // Wait for the client to get channelInactive.
            latch2.Wait();

            // Verify the client did not received a RST.
            Assert.Null(throwableRef.Value);
        }
示例#9
0
        public void Start()
        {
            try
            {
                _bootstrap.Group(_bossGroup, _workerGroup);
                _bootstrap.Channel <TcpServerSocketChannel>();
                _bootstrap.Option(ChannelOption.SoBacklog, 100);
                _bootstrap.ChildOption(ChannelOption.SoKeepalive, true);
                _bootstrap.Option(ChannelOption.TcpNodelay, true);
                _bootstrap.Option(ChannelOption.SoReuseport, true);
                _bootstrap.ChildOption(ChannelOption.SoReuseport, true);
                _bootstrap.Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default);
                _bootstrap.ChildOption(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default);
                _bootstrap.ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    pipeline.AddLast("DotNetty-enc", new LengthFieldPrepender(4));
                    pipeline.AddLast("DotNetty-dec", new LengthFieldBasedFrameDecoder(GlobalConfig.Config.MaxFrameLength, 0, 4, 0, 4));
                    pipeline.AddLast(new MasterMessageHandler((IChannelMessageHandler)this));
                }));

                _bootstrapChannel = _bootstrap.BindAsync(_localPort).Result;
                Logger.Log.Info(false, "主节点侦听端口:" + GlobalConfig.Config.MasterListenPort);
            }
            catch (Exception ex)
            {
                Logger.Log.Error(true, "", ex);
            }
        }
示例#10
0
        public void RunServerAsync()
        {
            IEventLoopGroup eventLoop;

            eventLoop = new MultithreadEventLoopGroup();
            try
            {
                // 服务器引导程序
                var bootstrap = new ServerBootstrap();
                bootstrap.Group(eventLoop);
                bootstrap.Channel <TcpServerSocketChannel>();
                bootstrap.ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    //解码
                    pipeline.AddLast(new ServerDecoder());
                    //服务端为读IDLE
                    pipeline.AddLast(new IdleStateHandler(60 * 5, 60 * 5, 60 * 5));//第一个参数为读,第二个为写,第三个为读写全部
                    //解码
                    pipeline.AddLast(new ServerEncoder());
                    //添加handler
                    pipeline.AddLast(new NettyServer());
                }));
                foreach (var server in _app.Value.Servers)
                {
                    bootstrap.BindAsync(server.Port);
                    LogHelper.Info("服务器启动:" + server.Name + "端口" + server.Port);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        /// <summary>
        /// 开启、关闭DotNetty服务
        /// </summary>
        private async void RaiseStartServerHandler()
        {
            StartServerButtonEnabled = false;

            IEventLoopGroup bossGroup   = new MultithreadEventLoopGroup(1);
            IEventLoopGroup workerGroup = new MultithreadEventLoopGroup();

            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap.Group(bossGroup, workerGroup);
                bootstrap.Channel <TcpServerSocketChannel>();
                bootstrap.ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    pipeline.AddLast(new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 4, 0, 4));
                    pipeline.AddLast(new MessagePackDecoder());
                    pipeline.AddLast(new LengthFieldPrepender(4));
                    pipeline.AddLast(new MessagePackEncoder());
                    pipeline.AddLast(DotNettyServerHandler);
                }));

                await bootstrap.BindAsync(ServerPort);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"连接服务异常:{ex.Message}");
            }
        }
示例#12
0
        void SingleCompositeBufferWrite0(ServerBootstrap sb, Bootstrap cb)
        {
            sb.ChildHandler(new ActionChannelInitializer <TcpChannel>(channel =>
            {
                channel.Pipeline.AddLast(new ServerHandler());
            }));

            var clientHandler = new ClientHandler();

            cb.Handler(new ActionChannelInitializer <TcpChannel>(channel =>
            {
                channel.Pipeline.AddLast(clientHandler);
            }));

            // start server
            Task <IChannel> task = sb.BindAsync(LoopbackAnyPort);

            Assert.True(task.Wait(DefaultTimeout), "Server bind timed out");
            this.serverChannel = task.Result;
            Assert.NotNull(this.serverChannel.LocalAddress);
            var endPoint = (IPEndPoint)this.serverChannel.LocalAddress;

            // connect to server
            task = cb.ConnectAsync(endPoint);
            Assert.True(task.Wait(DefaultTimeout), "Connect to server timed out");
            this.clientChannel = task.Result;
            Assert.NotNull(this.clientChannel.LocalAddress);

            IByteBuffer expected = NewCompositeBuffer(this.clientChannel.Allocator);

            clientHandler.AssertReceived(expected);
        }
示例#13
0
        static async Task RunHttpServerAsync(int port)
        {
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;
            }

            bossGroup   = new MultithreadEventLoopGroup(1);
            workerGroup = new MultithreadEventLoopGroup();

            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap.Group(bossGroup, workerGroup);
                bootstrap.Channel <TcpServerSocketChannel>();
                bootstrap.Option(ChannelOption.SoBacklog, 8192);
                bootstrap.ChildHandler(new ActionChannelInitializer <DotNetty.Transport.Channels.IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    pipeline.AddLast(new HttpServerCodec());
                    pipeline.AddLast(new HttpObjectAggregator(65536 * 5));
                    pipeline.AddLast(new HttpDecoder());
                }));

                bootstrapChannel = await bootstrap.BindAsync(port);

                LOGGER.Info("start http server success. listener port:[{}]", port);
            }
            catch (Exception e)
            {
                throw new Exception("start http server ERROR! \n" + e.ToString());
            }
        }
示例#14
0
        public async Task TestNotThrowBlockingOperationException()
        {
            IEventLoopGroup bossGroup   = new MultithreadEventLoopGroup(1);
            IEventLoopGroup workerGroup = new MultithreadEventLoopGroup(1);

            IChannelGroup allChannels = new DefaultChannelGroup();

            ServerBootstrap b = new ServerBootstrap();

            b.Group(bossGroup, workerGroup);
            b.ChildHandler(new ChannelInboundHandlerAdapter0(allChannels));
            b.Channel <TcpServerSocketChannel>();

            var ch = await b.BindAsync(0);

            allChannels.Add(ch);
            await allChannels.CloseAsync();

            await Task.WhenAll(
                bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5)),
                workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5))
                );

            await bossGroup.TerminationCompletion;
            await workerGroup.TerminationCompletion;
        }
示例#15
0
        public async void Start(int port)
        {
            IEventLoopGroup boss_group   = new MultithreadEventLoopGroup(1);
            IEventLoopGroup worker_group = new MultithreadEventLoopGroup(Args.Instance.Node.TcpNettyWorkThreadNum);

            try
            {
                ServerBootstrap bootstrap = new ServerBootstrap();

                bootstrap.Group(boss_group, worker_group);
                bootstrap.Channel <TcpServerSocketChannel>();
                bootstrap.Option(ChannelOption.SoKeepalive, true);
                bootstrap.Option(ChannelOption.MessageSizeEstimator, DefaultMessageSizeEstimator.Default);
                bootstrap.Option(ChannelOption.ConnectTimeout, TimeSpan.FromSeconds(Args.Instance.Node.ConnectionTimeout));
                bootstrap.Handler(new LoggingHandler());
                bootstrap.ChildHandler(new NettyChannelInitializer("", false));

                Logger.Info("Tcp listener started, bind port : " + port);

                this.channel = await bootstrap.BindAsync(port);
            }
            catch (System.Exception e)
            {
                Logger.Error(e.Message, e);
            }
            finally
            {
            }
        }
        void Run(ServerBootstrap sb, Bootstrap cb)
        {
            var serverInitializer = new ServerInitializer();

            sb.ChildHandler(serverInitializer);

            var clientInitializer = new ClientInitializer();

            cb.Handler(clientInitializer);

            // start server
            Task <IChannel> task = sb.BindAsync(LoopbackAnyPort);

            Assert.True(task.Wait(DefaultTimeout), "Server bind timed out");
            this.serverChannel = task.Result;
            Assert.NotNull(this.serverChannel.LocalAddress);
            var endPoint = (IPEndPoint)this.serverChannel.LocalAddress;

            // connect to server
            task = cb.ConnectAsync(endPoint);
            Assert.True(task.Wait(DefaultTimeout), "Connect to server timed out");
            this.clientChannel = task.Result;
            Assert.NotNull(this.clientChannel.LocalAddress);

            Assert.True(serverInitializer.Initialized.Wait(DefaultTimeout), "Channel initialize timed out");
            Assert.True(serverInitializer.Close());

            // Server connection closed will cause the client
            // to receive EOF and the channel should go inactive
            Assert.True(clientInitializer.Inactive.Wait(DefaultTimeout), "TcpChannel should fire Inactive if the server connection is closed.");
            Assert.Null(clientInitializer.ErrorCaught);
        }
        public void Test1()
        {
            // 作为源包转发服务端
            DispatcherEventLoopGroup bossGroup   = new DispatcherEventLoopGroup();
            WorkerEventLoopGroup     workerGroup = new WorkerEventLoopGroup(bossGroup, 1);
            ServerBootstrap          bootstrap   = new ServerBootstrap();

            bootstrap.Group(bossGroup, workerGroup);
            bootstrap.Channel <TcpServerChannel>();
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ||
                RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                bootstrap
                .Option(ChannelOption.SoReuseport, true)
                .ChildOption(ChannelOption.SoReuseaddr, true);
            }
            bootstrap
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                channel.Pipeline.AddLast("jt808Buffer", new DelimiterBasedFrameDecoder(int.MaxValue,
                                                                                       Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.BeginFlag }),
                                                                                       Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.EndFlag })));
                channel.Pipeline.AddLast("jt808Decode", new JT808ClientDecoder());
            }));
            bootstrap.BindAsync(6655);
            //作为设备上传
            byte[] bytes = "7E 02 00 00 26 12 34 56 78 90 12 00 7D 02 00 00 00 01 00 00 00 02 00 BA 7F 0E 07 E4 F1 1C 00 28 00 3C 00 00 18 10 15 10 10 10 01 04 00 00 00 64 02 02 00 7D 01 13 7E".ToHexBytes();
            SimpleTcpClient.WriteAsync(bytes);
            Thread.Sleep(10000);
            SimpleTcpClient.Down();
        }
示例#18
0
        /// <summary>
        /// 开启、关闭DotNetty服务
        /// </summary>
        private async void RaiseStartServerHandler()
        {
            StartServerButtonEnabled = false;

            IEventLoopGroup bossGroup   = new MultithreadEventLoopGroup(1);
            IEventLoopGroup workerGroup = new MultithreadEventLoopGroup();

            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap.Group(bossGroup, workerGroup);
                bootstrap.Channel <TcpServerSocketChannel>();
                bootstrap.ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    channel.Pipeline.AddLast(new ProtobufVarint32FrameDecoder())
                    .AddLast(new ProtobufDecoder(ChatInfo.Parser))
                    .AddLast(new ProtobufVarint32LengthFieldPrepender())
                    .AddLast(new ProtobufEncoder())
                    .AddLast(DotNettyServerHandler);
                }));

                await bootstrap.BindAsync(ServerPort);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"连接服务异常:{ex.Message}");
            }
        }
示例#19
0
        void BufRelease0(ServerBootstrap sb, Bootstrap cb)
        {
            var serverHandler = new BufWriterHandler();
            var clientHandler = new BufWriterHandler();

            sb.ChildHandler(serverHandler);
            cb.Handler(clientHandler);

            // start server
            Task <IChannel> task = sb.BindAsync(LoopbackAnyPort);

            Assert.True(task.Wait(DefaultTimeout), "Server bind timed out");
            this.serverChannel = task.Result;
            Assert.NotNull(this.serverChannel.LocalAddress);
            var endPoint = (IPEndPoint)this.serverChannel.LocalAddress;

            // connect to server
            task = cb.ConnectAsync(endPoint);
            Assert.True(task.Wait(DefaultTimeout), "Connect to server timed out");
            this.clientChannel = task.Result;
            Assert.NotNull(this.clientChannel.LocalAddress);

            // Ensure the server socket accepted the client connection *and* initialized pipeline successfully.
            Assert.True(serverHandler.Added.Wait(DefaultTimeout), "Channel HandlerAdded timed out");

            // and then close all sockets.
            this.serverChannel.CloseAsync().Wait(DefaultTimeout);
            this.clientChannel.CloseAsync().Wait(DefaultTimeout);

            serverHandler.Check();
            clientHandler.Check();

            serverHandler.Release();
            clientHandler.Release();
        }
        private void AsyncSettingsAck0(Http2FrameCodec codec, IChannelHandler multiplexer)
        {
            // The client expects 2 settings frames. One from the connection setup and one from this test.
            CountdownEvent             serverAckOneLatch           = new CountdownEvent(1);
            CountdownEvent             serverAckAllLatch           = new CountdownEvent(2);
            CountdownEvent             clientSettingsLatch         = new CountdownEvent(2);
            CountdownEvent             serverConnectedChannelLatch = new CountdownEvent(1);
            AtomicReference <IChannel> serverConnectedChannelRef   = new AtomicReference <IChannel>();

            _sb = new ServerBootstrap();
            _sb.Group(new MultithreadEventLoopGroup(1), new MultithreadEventLoopGroup());
            _sb.Channel <TcpServerSocketChannel>();
            _sb.ChildHandler(new ActionChannelInitializer <IChannel>(ch =>
            {
                ch.Pipeline.AddLast(codec);
                if (multiplexer != null)
                {
                    ch.Pipeline.AddLast(multiplexer);
                }
                ch.Pipeline.AddLast(new TestServerInboundHandler(serverAckOneLatch, serverAckAllLatch, serverConnectedChannelLatch, serverConnectedChannelRef));
            }));
            var loopback = IPAddress.IPv6Loopback;

            _serverChannel = _sb.BindAsync(loopback, 0).GetAwaiter().GetResult();

            _bs = new Bootstrap();
            _bs.Group(new MultithreadEventLoopGroup());
            _bs.Channel <TcpSocketChannel>();
            _bs.Handler(new ActionChannelInitializer <IChannel>(ch =>
            {
                var builder = Http2MultiplexCodecBuilder.ForClient(DISCARD_HANDLER.Instance);
                builder.AutoAckSettingsFrame = false;
                ch.Pipeline.AddLast(builder.Build());
                ch.Pipeline.AddLast(new TestClientInboundHandler(clientSettingsLatch));
            }));
            var port = ((IPEndPoint)_serverChannel.LocalAddress).Port;
            var ccf  = _bs.ConnectAsync(loopback, port);

            _clientChannel = ccf.GetAwaiter().GetResult();
            serverConnectedChannelLatch.Wait();
            _serverConnectedChannel = serverConnectedChannelRef.Value;

            _serverConnectedChannel.WriteAndFlushAsync(new DefaultHttp2SettingsFrame(new Http2Settings()
                                                                                     .MaxConcurrentStreams(10))).GetAwaiter().GetResult();

            clientSettingsLatch.Wait();

            // We expect a timeout here because we want to asynchronously generate the SETTINGS ACK below.
            Assert.False(serverAckOneLatch.Wait(TimeSpan.FromMilliseconds(300)));

            // We expect 2 settings frames, the initial settings frame during connection establishment and the setting frame
            // written in this test. We should ack both of these settings frames.
            _clientChannel.WriteAndFlushAsync(DefaultHttp2SettingsAckFrame.Instance).GetAwaiter().GetResult();
            _clientChannel.WriteAndFlushAsync(DefaultHttp2SettingsAckFrame.Instance).GetAwaiter().GetResult();

            serverAckAllLatch.Wait();
        }
示例#21
0
        public void TestReuseFd(ServerBootstrap sb, Bootstrap cb)
        {
            sb.ChildOption(ChannelOption.AutoRead, true);
            cb.Option(ChannelOption.AutoRead, true);

            // Use a number which will typically not exceed /proc/sys/net/core/somaxconn (which is 128 on linux by default
            // often).
            int numChannels = 100;
            AtomicReference <Exception> globalException = new AtomicReference <Exception>();
            AtomicInteger serverRemaining   = new AtomicInteger(numChannels);
            AtomicInteger clientRemaining   = new AtomicInteger(numChannels);
            IPromise      serverDonePromise = new DefaultPromise();
            IPromise      clientDonePromise = new DefaultPromise();

            sb.ChildHandler(new ActionChannelInitializer <IChannel>(sch =>
            {
                ReuseFdHandler sh = new ReuseFdHandler(
                    false,
                    globalException,
                    serverRemaining,
                    serverDonePromise);
                sch.Pipeline.AddLast("handler", sh);
            }));

            cb.Handler(new ActionChannelInitializer <IChannel>(sch =>
            {
                ReuseFdHandler ch = new ReuseFdHandler(
                    true,
                    globalException,
                    clientRemaining,
                    clientDonePromise);
                sch.Pipeline.AddLast("handler", ch);
            }));

            IChannel sc = sb.BindAsync().GetAwaiter().GetResult();

            for (int i = 0; i < numChannels; i++)
            {
                cb.ConnectAsync(sc.LocalAddress).ContinueWith(t =>
                {
                    if (!t.IsSuccess())
                    {
                        clientDonePromise.TrySetException(t.Exception);
                    }
                });
            }

            clientDonePromise.Task.GetAwaiter().GetResult();
            serverDonePromise.Task.GetAwaiter().GetResult();
            sc.CloseAsync().GetAwaiter().GetResult();
            if (globalException.Value is object)
            {
                throw globalException.Value;
            }
        }
示例#22
0
        public virtual void InitServer(string fsimage)
        {
            FSImageLoader loader = FSImageLoader.Load(fsimage);

            bootstrap.ChildHandler(new _ChannelInitializer_92(this, loader));
            channel = bootstrap.Bind(address).Sync().Channel();
            allChannels.AddItem(channel);
            address = (IPEndPoint)channel.LocalAddress();
            Log.Info("WebImageViewer started. Listening on " + address.ToString() + ". Press Ctrl+C to stop the viewer."
                     );
        }
示例#23
0
        private static void TestAutoCloseFalseDoesShutdownOutput0(bool allowHalfClosed,
                                                                  bool clientIsLeader,
                                                                  ServerBootstrap sb,
                                                                  Bootstrap cb)
        {
            const int      expectedBytes           = 100;
            CountdownEvent serverReadExpectedLatch = new CountdownEvent(1);
            CountdownEvent doneLatch             = new CountdownEvent(1);
            AtomicReference <Exception> causeRef = new AtomicReference <Exception>();
            IChannel serverChannel = null;
            IChannel clientChannel = null;

            try
            {
                cb.Option(ChannelOption.AllowHalfClosure, allowHalfClosed)
                .Option(ChannelOption.AutoClose, false)
                .Option(ChannelOption.SoLinger, 0);
                sb.ChildOption(ChannelOption.AllowHalfClosure, allowHalfClosed)
                .ChildOption(ChannelOption.AutoClose, false)
                .ChildOption(ChannelOption.SoLinger, 0);

                SimpleChannelInboundHandler <IByteBuffer> leaderHandler = new AutoCloseFalseLeader(expectedBytes,
                                                                                                   serverReadExpectedLatch, doneLatch, causeRef);
                SimpleChannelInboundHandler <IByteBuffer> followerHandler = new AutoCloseFalseFollower(expectedBytes,
                                                                                                       serverReadExpectedLatch, doneLatch, causeRef);
                sb.ChildHandler(new ActionChannelInitializer <IChannel>(ch =>
                {
                    ch.Pipeline.AddLast(clientIsLeader ? followerHandler : leaderHandler);
                }));

                cb.Handler(new ActionChannelInitializer <IChannel>(ch =>
                {
                    ch.Pipeline.AddLast(clientIsLeader ? leaderHandler : followerHandler);
                }));

                serverChannel = sb.BindAsync().GetAwaiter().GetResult();
                clientChannel = cb.ConnectAsync(serverChannel.LocalAddress).GetAwaiter().GetResult();

                doneLatch.Wait();
                Assert.Null(causeRef.Value);
            }
            finally
            {
                if (clientChannel != null)
                {
                    clientChannel.CloseAsync().GetAwaiter().GetResult();
                }
                if (serverChannel != null)
                {
                    serverChannel.CloseAsync().GetAwaiter().GetResult();
                }
            }
        }
        private async Task TestSingleCompositeBufferWrite0(ServerBootstrap sb, Bootstrap cb)
        {
            IChannel serverChannel = null;
            IChannel clientChannel = null;

            try
            {
                CountdownEvent           latch          = new CountdownEvent(1);
                AtomicReference <object> clientReceived = new AtomicReference <object>();
                sb.ChildHandler(new ActionChannelInitializer <IChannel>(ch =>
                {
                    ch.Pipeline.AddLast(new ChannelInboundHandlerAdapter2());
                }));
                cb.Handler(new ActionChannelInitializer <IChannel>(ch =>
                {
                    ch.Pipeline.AddLast(new ChannelInboundHandlerAdapter3(latch, clientReceived));
                }));

                serverChannel = await sb.BindAsync();

                clientChannel = await cb.ConnectAsync(serverChannel.LocalAddress);

                IByteBuffer expected = NewCompositeBuffer(clientChannel.Allocator);
                latch.Wait();
                object received = clientReceived.Value;
                if (received is IByteBuffer actual)
                {
                    Assert.Equal(expected, actual);
                    expected.Release();
                    actual.Release();
                }
                else
                {
                    expected.Release();
                    throw (Exception)received;
                }
            }
            finally
            {
                if (clientChannel != null)
                {
                    await clientChannel.CloseAsync();
                }
                if (serverChannel != null)
                {
                    await serverChannel.CloseAsync();
                }
                Task.WaitAll(
                    sb.Group().ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5)),
                    sb.ChildGroup().ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5)),
                    cb.Group().ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(5)));
            }
        }
示例#25
0
        internal virtual ServerBootstrap GetLocalServerBootstrap()
        {
            IEventLoopGroup serverGroup = new DefaultEventLoopGroup();
            ServerBootstrap sb          = new ServerBootstrap();

            sb.Group(serverGroup);
            sb.Channel <LocalServerChannel>();
            sb.ChildHandler(new ActionChannelInitializer <LocalChannel>(ch =>
            {
            }));
            return(sb);
        }
示例#26
0
 protected void Init()
 {
     _bootstrap.Group(_bossEventLoopGroup, _workerEventLoopGroup);
     _bootstrap.Channel <TcpServerSocketChannel>();
     _bootstrap.Option(ChannelOption.SoLinger, 0);
     _bootstrap.Option(ChannelOption.SoBacklog, Backlog);
     _bootstrap.Handler(new LoggingHandler(LogLevel.INFO));
     _bootstrap.ChildHandler(new InboundSessionInitializer(inboundSession));
     _bootstrap.ChildOption(ChannelOption.SoLinger, 0);
     _bootstrap.ChildOption(ChannelOption.SoKeepalive, true);
     _bootstrap.ChildOption(ChannelOption.TcpNodelay, true);
     _bootstrap.ChildOption(ChannelOption.SoReuseaddr, true);
 }
示例#27
0
        private static void TestAllDataReadAfterHalfClosure0(bool autoRead,
                                                             ServerBootstrap sb, Bootstrap cb)
        {
            const int      totalServerBytesWritten = 1024 * 16;
            const int      numReadsPerReadLoop     = 2;
            CountdownEvent serverInitializedLatch  = new CountdownEvent(1);
            CountdownEvent clientReadAllDataLatch  = new CountdownEvent(1);
            CountdownEvent clientHalfClosedLatch   = new CountdownEvent(1);
            AtomicInteger  clientReadCompletes     = new AtomicInteger();
            IChannel       serverChannel           = null;
            IChannel       clientChannel           = null;

            try
            {
                cb.Option(ChannelOption.AllowHalfClosure, true)
                .Option(ChannelOption.AutoRead, autoRead)
                .Option(ChannelOption.RcvbufAllocator, new TestNumReadsRecvByteBufAllocator(numReadsPerReadLoop));

                sb.ChildHandler(new ActionChannelInitializer <IChannel>(ch =>
                {
                    ch.Pipeline.AddLast(new ChannelInboundHandlerAdapter2(totalServerBytesWritten, serverInitializedLatch));
                }));

                cb.Handler(new ActionChannelInitializer <IChannel>(ch =>
                {
                    ch.Pipeline.AddLast(new ChannelInboundHandlerAdapter3(autoRead, totalServerBytesWritten,
                                                                          clientHalfClosedLatch, clientReadAllDataLatch, clientReadCompletes));
                }));

                serverChannel = sb.BindAsync().GetAwaiter().GetResult();
                clientChannel = cb.ConnectAsync(serverChannel.LocalAddress).GetAwaiter().GetResult();
                clientChannel.Read();

                serverInitializedLatch.Wait();
                clientReadAllDataLatch.Wait();
                clientHalfClosedLatch.Wait();
                Assert.True(totalServerBytesWritten / numReadsPerReadLoop + 10 > clientReadCompletes.Value,
                            "too many read complete events: " + clientReadCompletes.Value);
            }
            finally
            {
                if (clientChannel != null)
                {
                    clientChannel.CloseAsync().GetAwaiter().GetResult();
                }
                if (serverChannel != null)
                {
                    serverChannel.CloseAsync().GetAwaiter().GetResult();
                }
            }
        }
示例#28
0
        public async Task RunServerAsync()
        {
            OnSubMessage?.Invoke("服务启动中......", "重要");
            //第一步:创建ServerBootstrap实例
            var bootstrap = new ServerBootstrap();
            //第二步:绑定事件组
            IEventLoopGroup mainGroup = new MultithreadEventLoopGroup(1); //主工作线程组
            IEventLoopGroup workGroup = new MultithreadEventLoopGroup();  //工作线程组

            bootstrap.Group(mainGroup, workGroup);
            //第三步:绑定服务端的通道
            bootstrap.Channel <TcpServerSocketChannel>();// 设置通道模式为TcpSocket
            //第四步:配置处理器
            bootstrap.Option(ChannelOption.SoBacklog, 8192);
            bootstrap.ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                //pipeline.AddLast(new HttpServerCodec());
                //pipeline.AddLast(new HttpObjectAggregator(65536));
                pipeline.AddLast(new TcpServerHandler());
            }));
            //第五步:配置主机和端口号
            string hostName = Dns.GetHostName();

            IPAddress[] ipAddresses = Dns.GetHostAddresses(hostName);
            ipAddresses = ipAddresses.Where(m => m.ToString().IsIPv4()).ToArray();
            var       host             = ConfigHelper.Configuration["ServerConfig:Host"];
            bool      trueAddress      = ipAddresses.Any(m => host.Equals(m.ToString()));
            IPAddress iPAddress        = trueAddress ? IPAddress.Parse(host) : ipAddresses[0];
            var       port             = ConfigHelper.Configuration["ServerConfig:Port"];
            IChannel  bootstrapChannel = await bootstrap.BindAsync(iPAddress, int.Parse(port));

            OnSubMessage?.Invoke("服务启动成功", "重要");
            OnMessage?.Invoke($"已监听http://{iPAddress}:{int.Parse(port)}");
            //第六步:停止服务
            OnMessage?.Invoke("输入Stop停止服务");
            string inputKey = string.Empty;

            while (!string.Equals(inputKey, "Stop", StringComparison.Ordinal))
            {
                inputKey = OnGetCommand?.Invoke();
                if (!string.Equals(inputKey, "Stop", StringComparison.Ordinal))
                {
                    OnException?.Invoke(new Exception("未识别命令请重新输入"));
                }
            }
            OnSubMessage?.Invoke("正在停止服务......", "重要");
            await bootstrapChannel.CloseAsync();

            OnSubMessage?.Invoke("服务已停止", "重要");
        }
示例#29
0
        /// <summary>
        /// 开启、关闭DotNetty服务
        /// </summary>
        private async void RaiseStartServerHandler()
        {
            IsStartServer            = !IsStartServer;
            StartServerButtonContent = (IsStartServer ? "关闭服务" : "开启服务");
            if (!IsStartServer)
            {
                StopServer();
                return;
            }

            // 主工作线程组,设置为1个线程
            IEventLoopGroup bossGroup = new MultithreadEventLoopGroup(1);
            // 工作线程组,默认为内核数*2的线程数
            IEventLoopGroup workerGroup = new MultithreadEventLoopGroup();

            try
            {
                //声明一个服务端Bootstrap,每个Netty服务端程序,都由ServerBootstrap控制,
                //通过链式的方式组装需要的参数
                var bootstrap = new ServerBootstrap();
                bootstrap.Group(bossGroup, workerGroup);                                    // 设置主和工作线程组
                bootstrap.Channel <TcpServerSocketChannel>();                               // 设置通道模式为TcpSocket
                bootstrap.ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    //工作线程连接器 是设置了一个管道,服务端主线程所有接收到的信息都会通过这个管道一层层往下传输
                    //同时所有出栈的消息 也要这个管道的所有处理器进行一步步处理
                    IChannelPipeline pipeline = channel.Pipeline;

                    //配置编码解码器
                    pipeline.AddLast("frameDecoder", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 4, 0, 4));
                    pipeline.AddLast("msgPackDecoder", new MessagePackDecoder());
                    pipeline.AddLast("frameEncoder", new LengthFieldPrepender(4));
                    pipeline.AddLast("msgPackEncoder", new MessagePackEncoder());

                    // IdleStateHandler 心跳
                    //服务端为读IDLE
                    pipeline.AddLast(new IdleStateHandler(150, 0, 0));      //第一个参数为读,第二个为写,第三个为读写全部

                    //业务handler ,这里是实际处理业务的Handler
                    pipeline.AddLast("handler", DotNettyServerHandler);
                }));

                // bootstrap绑定到指定端口的行为 就是服务端启动服务,同样的Serverbootstrap可以bind到多个端口
                serverChannel = await bootstrap.BindAsync(ServerPort);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
示例#30
0
 void Bootstrap()
 {
     bootstrap.Group(parentEventLoopGroup, eventLoopGroup);
     bootstrap.Option(ChannelOption.SoBacklog, ListenBacklogSize);
     bootstrap.ChildOption(ChannelOption.Allocator, PooledByteBufferAllocator.Default);
     bootstrap.Channel <TcpServerSocketChannel>();
     bootstrap.Option(ChannelOption.ConnectTimeout, DefaultConnectionIdleTimeout);
     bootstrap.ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
     {
         IChannelPipeline pipeline = channel.Pipeline;
         pipeline.AddLast(new LengthFieldBasedFrameDecoder(ByteOrder.BigEndian, 4096, 1, 4, -5, 0, true));
         pipeline.AddLast(new BmpDecoder(), new BmpMessageHandler());
     }));
 }