Exemple #1
0
        static async Task RunClientAsync()
        {
            var group = new MultithreadEventLoopGroup();

            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                .Group(group)
                .Channel <TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(
                    new ActionChannelInitializer <ISocketChannel>(
                        channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    pipeline.AddLast(new LoggingHandler());
                    pipeline.AddLast("framing-enc", new LengthFieldPrepender(2));
                    pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));

                    pipeline.AddLast("echo", new EchoClientHandler());
                }));

                IChannel clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8007));

                // 建立死循环,类同于While(true)
//                for (;;)
//                {
//                    Console.WriteLine("input you name:");
//                    // 根据设置建立缓存区大小
//                    IByteBuffer initialMessage = Unpooled.Buffer(256);
//                    string r = Console.ReadLine();
//                    // 将数据流写入缓冲区
//                    initialMessage.WriteBytes(Encoding.UTF8.GetBytes(r ?? throw new InvalidOperationException()));
//                    // 将缓冲区数据流写入到管道中
//                    await clientChannel.WriteAndFlushAsync(initialMessage);
//
//                    if (r.Contains("bye")) break;
//                }

                Console.ReadKey();

                Console.WriteLine("byebye");


                await clientChannel.CloseAsync();
            }
            finally
            {
                await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            }
        }
        /// <summary>
        /// Populates the channel pipeline in order to upgrade a connection to WebSocket.
        /// </summary>
        public static void populateWSPipelineForHandshake(IChannel ch, IChannelHandler wsHandshakeHandler)
        {
            IChannelPipeline p = ch.Pipeline;

            /*
             * Note: since the channel pipeline was filled by populateHttpPipeline(),
             * we must remove the HTTP user-defined handler before of upgrading the channel
             */
            p.Remove(READER_KEY);
            p.AddLast(new HttpObjectAggregator(8192));
            p.AddLast(WebSocketClientCompressionHandler.Instance);
            p.AddLast(wsHandshakeHandler);
        }
Exemple #3
0
        public async Task Start()
        {
            _group        = new MultithreadEventLoopGroup();
            _scertHandler = new ScertServerHandler();

            TimeLostConnection = null;

            // Add client on connect
            _scertHandler.OnChannelActive += (channel) =>
            {
            };

            // Remove client on disconnect
            _scertHandler.OnChannelInactive += async(channel) =>
            {
                Logger.Error($"Lost connection to MPS");
                TimeLostConnection = DateTime.UtcNow;
                await Stop();
            };

            // Queue all incoming messages
            _scertHandler.OnChannelMessage += (channel, message) =>
            {
                // Add to queue
                _mpsRecvQueue.Enqueue(message);

                // Log if id is set
                if (message.CanLog())
                {
                    Logger.Info($"MPS RECV {channel}: {message}");
                }
            };

            _bootstrap = new Bootstrap();
            _bootstrap
            .Group(_group)
            .Channel <TcpSocketChannel>()
            .Option(ChannelOption.TcpNodelay, true)
            .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;

                pipeline.AddLast(new ScertEncoder());
                pipeline.AddLast(new ScertIEnumerableEncoder());
                pipeline.AddLast(new ScertTcpFrameDecoder(DotNetty.Buffers.ByteOrder.LittleEndian, Constants.MEDIUS_MESSAGE_MAXLEN, 1, 2, 0, 0, false));
                pipeline.AddLast(new ScertDecoder(_sessionCipher, _serverKey));
                pipeline.AddLast(_scertHandler);
            }));

            await ConnectMPS();
        }
Exemple #4
0
        static async Task RunServerAsync()
        {
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;
            }

            Console.WriteLine($"Server garbage collection: {GCSettings.IsServerGC}");
            Console.WriteLine($"Current latency mode for garbage collection: {GCSettings.LatencyMode}");

            IEventLoopGroup group;
            IEventLoopGroup workGroup;
            var             dispatcher = new DispatcherEventLoopGroup();

            group     = dispatcher;
            workGroup = new WorkerEventLoopGroup(dispatcher);
            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap.Group(group, workGroup);
                bootstrap.Channel <TcpServerChannel>();
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ||
                    RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    bootstrap
                    .Option(ChannelOption.SoReuseport, true)
                    .ChildOption(ChannelOption.SoReuseaddr, true);
                }
                bootstrap
                .Option(ChannelOption.SoBacklog, 8192)
                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    //pipeline.AddLast("encoder", new HttpResponseEncoder());
                    pipeline.AddLast(new HttpServerCodec());
                    pipeline.AddLast(new HttpObjectAggregator(ConfigHelper.GetValue <int>("maxContentLength")));
                    pipeline.AddLast("handler", new HttpServerHandler());
                }));

                IChannel bootstrapChannel = await bootstrap.BindAsync(IPAddress.IPv6Any, ConfigHelper.GetValue <int>("httpPort"));

                Console.WriteLine($"Httpd started. Listening on {bootstrapChannel.LocalAddress}");
                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                group.ShutdownGracefullyAsync().Wait();
            }
        }
Exemple #5
0
        static async Task RunServerAsync()
        {
            var bossGroup   = new MultithreadEventLoopGroup();
            var workerGroup = new MultithreadEventLoopGroup();

            X509Certificate2 tlsCertificate = null;

            if (ServerSettings.IsSsl)
            {
                tlsCertificate = new X509Certificate2("filename", "password");
            }

            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup)                                                // 设置主和工作线程组
                .Channel <TcpServerSocketChannel>()                                           // 设置通道模式为TcpSocket
                .Option(ChannelOption.SoBacklog, 100)                                         // 设置网络IO参数等,这里可以设置很多参数,当然你对网络调优和参数设置非常了解的话,你可以设置,或者就用默认参数吧
                .Handler(new LoggingHandler("SRV-LSTN"))                                      //在主线程组上设置一个打印日志的处理器
                .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {                                                                             //工作线程连接器 是设置了一个管道,服务端主线程所有接收到的信息都会通过这个管道一层层往下传输//同时所有出栈的消息 也要这个管道的所有处理器进行一步步处理
                    IChannelPipeline pipeline = channel.Pipeline; if (tlsCertificate != null) //Tls的加解密
                    {
                        pipeline.AddLast("tls", TlsHandler.Server(tlsCertificate));
                    }                                                                                               //日志拦截器
                    pipeline.AddLast(new LoggingHandler("SRV-CONN"));                                               //出栈消息,通过这个handler 在消息顶部加上消息的长度
                    pipeline.AddLast("framing-enc", new LengthFieldPrepender(2));                                   //入栈消息通过该Handler,解析消息的包长信息,并将正确的消息体发送给下一个处理Handler,该类比较常用,后面单独说明
                    pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2)); //业务handler ,这里是实际处理Echo业务的Handler
                    pipeline.AddLast("echo", new EchoServerHandler());
                }));
                // bootstrap绑定到指定端口的行为 就是服务端启动服务,同样的Serverbootstrap可以bind到多个端口
                IChannel boundChannel = await bootstrap.BindAsync(ServerSettings.Port);

                Console.ReadLine();//关闭服务

                await boundChannel.CloseAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            finally
            {
                //释放工作组线程
                await Task.WhenAll(
                    bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)),
                    workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)));
            }
        }
Exemple #6
0
        public async Task StartAsync()
        {
            IEventLoopGroup workerGroup = new MultithreadEventLoopGroup();

            if (_options.ProtocolType == ProtocolType.Tcp)
            {
                IEventLoopGroup bossGroup = new MultithreadEventLoopGroup(1);
                var             bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>();

                bootstrap
                .Option(ChannelOption.SoBacklog, 8192)
                .Handler(new LoggingHandler("SRV-LSTN"))
                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    if (_options.Ssl)
                    {
                        var tlsCertificate = new X509Certificate2(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "dotnetty.com.pfx"), "password");
                        pipeline.AddLast("tls", TlsHandler.Server(tlsCertificate));
                    }

                    pipeline.AddLast(new LoggingHandler("SRV-CONN"));
                    pipeline.AddLast(new IdleStateHandler(TimeSpan.FromHours(8), TimeSpan.FromHours(8), TimeSpan.FromHours(8)));
                    if (_options.SocketMode == SocketMode.Socket)
                    {
                        pipeline.AddLast("framing-enc", new DotNettyMessageEncoder(_packetCodec));
                        pipeline.AddLast("framing-dec", new DotNettyMessageDecoder(_packetCodec));
                        pipeline.AddLast(new SocketServerHandler <PacketInfo>(_serviceProvider, true));
                    }
                    else    // websocket support
                    {
                        pipeline.AddLast(new HttpServerCodec());
                        pipeline.AddLast("framing-enc", new DotNettyMessageWebSocketEncoder(_packetCodec));
                        pipeline.AddLast(new HttpObjectAggregator(65536));
                        pipeline.AddLast(new WebSocketServerHandler(_serviceProvider, _options));
                    }
                }));
                _boundChannel = await bootstrap.BindAsync(_options.Port).ConfigureAwait(false);
            }
            else
            {
                var bootstrap = new Bootstrap();
                bootstrap
                .Group(workerGroup)
                .Channel <SocketDatagramChannel>();
                _boundChannel = await bootstrap.BindAsync(_options.Port).ConfigureAwait(false);
            }
        }
Exemple #7
0
        public void InitClient()
        {
            try
            {
                bootstrap
                .Group(group)
                .Channel <TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Option(ChannelOption.ConnectTimeout, TimeSpan.FromSeconds(3))
                .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    //pipeline.AddLast("log", new LoggingHandler("Log"));

                    pipeline.AddLast("timeout", new IdleStateHandler(0, 0, 30));

                    pipeline.AddLast("connectionWatchdog", new ConnectionWatchdog(bootstrap, Config, sessionMap, timer, loggerFactory));

                    pipeline.AddLast("activeIdleStateTrigger", new ActiveIdleStateTrigger(loggerFactory));

                    pipeline.AddLast("enc", new Cmpp2Encoder(loggerFactory));

                    pipeline.AddLast("dec", new Cmpp2Decoder(loggerFactory, ushort.MaxValue, 0, 4, -4, 0));

                    pipeline.AddLast(eventExecutorGroup, "submit", new CmppSubmitRespHandler(smsHandler, matchQueue, loggerFactory));

                    pipeline.AddLast(eventExecutorGroup, "deliver", new CmppDeliverHandler(smsHandler, loggerFactory));

                    pipeline.AddLast(eventExecutorGroup, "connetc", new CmppConnectHandler(Config, sessionMap, ConnectCallBack, timer, loggerFactory));

                    pipeline.AddLast(eventExecutorGroup, "active", new CmppActiveHandler(loggerFactory));

                    pipeline.AddLast(eventExecutorGroup, "connectClose", new ConnectCloseHandler(sessionMap, smsHandler.ConnectCloseCompleteCallBack, loggerFactory));
                }));

                if (Config.AutoReConnect)
                {
                    ForeverReConnect();
                }
                else
                {
                    //ConnectAsync().GetAwaiter().GetResult();
                }
            }
            catch (Exception e)
            {
                logger.Error(e);
                group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            }
        }
Exemple #8
0
        protected virtual void InitChannel(IChannel channel)
        {
            IChannelPipeline pipeline = channel.Pipeline;

            pipeline.AddLast(new LoggingHandler("SRV-CONN"));
            pipeline.AddLast("framing-enc", new MsgEncoder());
            pipeline.AddLast("framing-dec", new MsgDecoder());

            Connection handler = CreateConnection();

            handler.connected    += OnConnect;
            handler.disconnected += OnDisconnect;
            pipeline.AddLast("handler", handler);
        }
Exemple #9
0
        static async Task RunClientAsync()
        {
            var eventListener = new ObservableEventListener();

            eventListener.LogToConsole();
            eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.Verbose);

            var group = new MultithreadEventLoopGroup();

            X509Certificate2 cert       = null;
            string           targetHost = null;

            if (EchoClientSettings.IsSsl)
            {
                cert       = new X509Certificate2("dotnetty.com.pfx", "password");
                targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
            }
            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                .Group(group)
                .Channel <TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    if (cert != null)
                    {
                        pipeline.AddLast(new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));
                    }
                    pipeline.AddLast(new LengthFieldPrepender(2));
                    pipeline.AddLast(new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));

                    pipeline.AddLast(new EchoClientHandler());
                }));

                IChannel bootstrapChannel = await bootstrap.ConnectAsync(new IPEndPoint(EchoClientSettings.Host, EchoClientSettings.Port));

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                group.ShutdownGracefullyAsync().Wait(1000);
                eventListener.Dispose();
            }
        }
Exemple #10
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());
     }));
 }
Exemple #11
0
        static async Task RunServerAsync()
        {
            IEventLoopGroup bossGroup;
            IEventLoopGroup workerGroup;

            bossGroup   = new MultithreadEventLoopGroup(1);
            workerGroup = new MultithreadEventLoopGroup();
            X509Certificate2 tlsCertificate = null;

            if (ServerSetting.IsSsl)
            {
                tlsCertificate = new X509Certificate2(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "dotnetty.com.pfx"), "password");
            }
            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup);

                bootstrap.Channel <TcpServerSocketChannel>();

                bootstrap
                .Option(ChannelOption.SoBacklog, 100)
                .Handler(new LoggingHandler("SRV-LSTN"))
                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    if (tlsCertificate != null)
                    {
                        pipeline.AddLast("tls", TlsHandler.Server(tlsCertificate));
                    }
                    pipeline.AddLast("framing-enc", new LengthFieldPrepender(2));
                    pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));

                    pipeline.AddLast("echo", new EchoServerHandler());
                }));

                IChannel boundChannel = await bootstrap.BindAsync(ServerSetting.Port);

                Console.ReadLine();

                await boundChannel.CloseAsync();
            }
            finally
            {
                await Task.WhenAll(
                    bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)),
                    workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)));
            }
        }
Exemple #12
0
        protected override void Init(IChannel channel)
        {
            IDictionary <ChannelOption, object> options = this.Options();

            foreach (KeyValuePair <ChannelOption, object> e in options)
            {
                try
                {
                    if (!channel.Configuration.SetOption(e.Key, e.Value))
                    {
                        BootstrapEventSource.Log.Warning("Unknown channel option: " + e);
                    }
                }
                catch (Exception ex)
                {
                    BootstrapEventSource.Log.Warning("Failed to set a channel option: " + channel, ex);
                }
            }

            // todo: attrs
            //Map<AttributeKey<?>, Object> attrs = attrs();
            //lock (attrs) {
            //    foreach (var e in attrs.entrySet()) {
            //        AttributeKey<object> key = (AttributeKey<object>) e.getKey();
            //        channel.attr(key).set(e.getValue());
            //    }
            //}

            IChannelPipeline p = channel.Pipeline;

            if (this.Handler() != null)
            {
                p.AddLast(this.Handler());
            }

            IEventLoopGroup currentChildGroup   = this.childGroup;
            IChannelHandler currentChildHandler = this.childHandler;

            KeyValuePair <ChannelOption, object>[] currentChildOptions = this.childOptions.ToArray();
            // todo: attrs
            //Entry<AttributeKey<?>, Object>[] currentChildAttrs = this.childAttrs.ToArray();

            Func <IChannelConfiguration, bool> childConfigSetupFunc = CompileOptionsSetupFunc(this.childOptions);

            p.AddLast(new ActionChannelInitializer <IChannel>(ch =>
            {
                ch.Pipeline.AddLast(new ServerBootstrapAcceptor(currentChildGroup, currentChildHandler,
                                                                childConfigSetupFunc /*, currentChildAttrs*/));
            }));
        }
Exemple #13
0
        static async Task Main(string[] args)
        {
            ExampleHelper.SetConsoleLogger();

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

            var stringEncoder = new StringEncoder();
            var stringDecoder = new StringDecoder();
            var serverHandler = new SecureChatServerHandler();

            X509Certificate2 tlsCertificate = null;

            if (ServerSettings.IsSsl)
            {
                tlsCertificate = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password");
            }

            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, 100)
                .Handler(new LoggingHandler("LSTN"))
                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    if (tlsCertificate != null)
                    {
                        pipeline.AddLast(TlsHandler.Server(tlsCertificate));
                    }

                    pipeline.AddLast(new LoggingHandler("CONN"));
                    pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                    pipeline.AddLast(stringEncoder, stringDecoder, serverHandler);
                }));

                IChannel bootstrapChannel = await bootstrap.BindAsync(ServerSettings.Port);

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }
        }
Exemple #14
0
        void ConfigureClearText(IChannel ch)
        {
            IChannelPipeline                   p              = ch.Pipeline;
            HttpServerCodec                    sourceCodec    = new HttpServerCodec();
            HttpServerUpgradeHandler           upgradeHandler = new HttpServerUpgradeHandler(sourceCodec, UpgradeCodecFactory);
            CleartextHttp2ServerUpgradeHandler cleartextHttp2ServerUpgradeHandler =
                new CleartextHttp2ServerUpgradeHandler(sourceCodec, upgradeHandler,
                                                       new HelloWorldHttp2HandlerBuilder().Build());

            p.AddLast(cleartextHttp2ServerUpgradeHandler);
            p.AddLast(new HttpMessageHandler(this.maxHttpContentLength));

            p.AddLast(new UserEventLogger());
        }
        public void StartListening()
        {
            TCPVoiceRouter.Logger.Log(NLog.LogLevel.Info, "VOIP Listener INIT");
            var bossGroup   = new MultithreadEventLoopGroup();
            var workerGroup = new MultithreadEventLoopGroup();

            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, 100)
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(new LoggingHandler(LogLevel.ERROR))
                .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    pipeline.AddLast(new LengthFieldBasedFrameDecoder(ByteOrder.LittleEndian, 1024, 0, 2, -2, 0,
                                                                      true));
                    pipeline.AddLast(new VOIPPacketHandler(_clientsList));
                })).ChildOption(ChannelOption.TcpNodelay, true);

                TCPVoiceRouter.Logger.Log(NLog.LogLevel.Info,
                                          "VOIP Listener Binding to " + _serverSettings.ServerListeningPort() + 1);
                Task <IChannel> bootstrapChannel = bootstrap.BindAsync(_serverSettings.ServerListeningPort() + 1);

                bootstrapChannel.Wait(5000);


                TCPVoiceRouter.Logger.Log(NLog.LogLevel.Info,
                                          "VOIP Listener Bound to " + _serverSettings.ServerListeningPort() + 1);

                TCPVoiceRouter.Logger.Log(NLog.LogLevel.Info, "VOIP Listener Waiting for Shutdown...");
                //wait here for shutdown
                _serverShutdownToken.Token.WaitHandle.WaitOne();
                TCPVoiceRouter.Logger.Log(NLog.LogLevel.Info, "VOIP Listener Waiting for Shutting down...");

                var task = bootstrapChannel.Result.CloseAsync();

                task.Wait(10000);
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }

            TCPVoiceRouter.Logger.Log(NLog.LogLevel.Info, "VOIP Listener Shutdown");
        }
Exemple #16
0
        static async Task RunClientAsync()
        {
            ExampleHelper.SetConsoleLogger();

            var group = new MultithreadEventLoopGroup();

            X509Certificate2 cert       = null;
            string           targetHost = null;

            if (ClientSettings.IsSsl)
            {
                cert       = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password");
                targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
            }
            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                .Group(group)
                .Channel <TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    if (cert != null)
                    {
                        //Netty支持Tls加密传输,TlsHandler类可以在开发人员无须关心加密传输时字节码的变化,只关心自己的业务代码即可。在管道处理的第一个配置该类即可
                        pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));
                    }
                    pipeline.AddLast(new LoggingHandler());
                    //LengthFieldPrepender 会在实际发送前在将数据的长度放置在数据前,本例中使用2个字节来存储数据的长度。
                    pipeline.AddLast("framing-enc", new LengthFieldPrepender(2));
                    //LengthFieldBasedFrameDecoder 比较常用,会在解码前用于解析数据,用于读取数据包的头信息,特别是包长,并等待数据达到包长后再交由下一个handler处理。 参数说明 以下是Amp协议的参数值,并注释了意义
                    pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));

                    pipeline.AddLast("echo", new EchoClientHandler());
                }));

                IChannel clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(ClientSettings.Host, ClientSettings.Port));

                Console.ReadLine();

                await clientChannel.CloseAsync();
            }
            finally
            {
                await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            }
        }
Exemple #17
0
        public async Task RunServerAsync(TcpServerParams args)
        {
            IEventLoopGroup bossGroup;
            IEventLoopGroup workerGroup;

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

            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, args.Backlog) //设置网络IO参数等
                .Option(ChannelOption.SoKeepalive, true)       //保持连接
                .Handler(new LoggingHandler("SRV-LSTN"))       //在主线程组上设置一个打印日志的处理器
                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    //工作线程连接器 是设置了一个管道,服务端主线程所有接收到的信息都会通过这个管道一层层往下传输
                    //同时所有出栈的消息 也要这个管道的所有处理器进行一步步处理
                    IChannelPipeline pipeline = channel.Pipeline;

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

                    //出栈消息,通过这个handler 在消息顶部加上消息的长度
                    pipeline.AddLast("framing-enc", new LengthFieldPrepender(2));
                    //入栈消息通过该Handler,解析消息的包长信息,并将正确的消息体发送给下一个处理Handler
                    pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));

                    pipeline.AddLast("NettyServer", new ServerHandler());
                }));

                IChannel boundChannel = await bootstrap.BindAsync(args.ServerPort);

                //运行至此处,服务启动成功
                IsServerRunning = true;

                ClosingArrivedEvent.Reset();
                ClosingArrivedEvent.WaitOne();
                await boundChannel.CloseAsync();
            }
            finally
            {
                await Task.WhenAll(
                    bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)),
                    workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)));
            }
        }
Exemple #18
0
        static async Task RunClientAsync()
        {
            var group = new MultithreadEventLoopGroup();

            X509Certificate2 cert       = null;
            string           targetHost = null;

            if (true)
            {
                cert       = new X509Certificate2(Path.Combine(Directory.GetCurrentDirectory(), "dotnetty.com.pfx"), "password");
                targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
            }
            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                .Group(group)
                .Channel <TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    //if (cert != null)
                    //{
                    //    pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));
                    //}
                    pipeline.AddLast(new LoggingHandler());
                    pipeline.AddLast("framing-enc", new LengthFieldPrepender(2));
                    pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));

                    pipeline.AddLast("echo", new EchoClientHandler());
                }));

                IChannel clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8007));

                Console.WriteLine("Client Start");
                Console.ReadLine();
                await clientChannel.CloseAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            }
        }
Exemple #19
0
        static async Task RunClientAsync()
        {
            ExampleHelper.SetConsoleLogger();

            var group = new MultithreadEventLoopGroup();

            X509Certificate2 cert       = null;
            string           targetHost = null;

            if (ClientSettings.IsSsl)
            {
                cert       = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password");
                targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
            }
            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                .Group(group)
                .Channel <TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    if (cert != null)
                    {
                        pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));
                    }
                    pipeline.AddLast(new LoggingHandler());
                    pipeline.AddLast("framing-enc", new LengthFieldPrepender(2));
                    pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));
                    new StringEncoder();
                    new StringDecoder();

                    pipeline.AddLast("echo", new EchoClientHandler());
                }));

                IChannel clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(ClientSettings.Host, ClientSettings.Port));

                Console.ReadLine();

                await clientChannel.CloseAsync();
            }
            finally
            {
                await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            }
        }
Exemple #20
0
        //public static TcpSocketClient Instance = new TcpSocketClient();

        public bool init(TcpChannelConfig channelConfig)
        {
            this.channelConfig = channelConfig;

            group = new MultithreadEventLoopGroup();

            X509Certificate2 cert       = null;
            string           targetHost = null;

            if (channelConfig.UseSSL)
            {
                cert       = new X509Certificate2("dotnetty.com.pfx", "password");
                targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
            }

            try
            {
                bootstrap = new Bootstrap();
                bootstrap
                .Group(group)
                .Channel <TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    if (cert != null)
                    {
                        pipeline.AddLast("tls",
                                         new TlsHandler(
                                             stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true),
                                             new ClientTlsSettings(targetHost)));
                    }

                    pipeline.AddLast(new LoggingHandler());
                    pipeline.AddLast("framing-enc", new LengthFieldPrepender(2));
                    pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));
                    pipeline.AddLast("tcp-handler", new TcpChannelHandler(this));
                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                return(false);
            }

            return(true);
        }
Exemple #21
0
        static async Task RunServerAsync()
        {
            Console.Title = "MultipleProtocols.Server";
            var logLevel = LogLevel.DEBUG;

            InternalLoggerFactory.DefaultFactory.AddProvider(new ConsoleLoggerProvider((s, level) => true, false));

            var serverPort = 8080;

            var bossGroup   = new MultithreadEventLoopGroup(1); //  accepts an incoming connection
            var workerGroup = new MultithreadEventLoopGroup();  // handles the traffic of the accepted connection once the boss accepts the connection and registers the accepted connection to the worker

            var encoder = new StringEncoder();
            var decoder = new ProtocolSelectorDecoder(logRawMessages: true);

            try
            {
                var bootstrap = new ServerBootstrap();

                bootstrap
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, 100)     // maximum queue length for incoming connection
                .Handler(new LoggingHandler(logLevel))
                .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    pipeline.AddLast(new LineBasedFrameDecoder(80));
                    pipeline.AddLast(new IdleStateHandler(5, 5, 0));
                    pipeline.AddLast(encoder);     // Encoder has to be before every handler in the pipeline that writes data e.g. TerminateIdleConnectionHandler.
                    pipeline.AddLast(new TerminateIdleConnectionHandler());

                    pipeline.AddLast(decoder);
                }));

                IChannel bootstrapChannel = await bootstrap.BindAsync(serverPort);

                Console.WriteLine("Let us test the server in a command prompt");
                Console.WriteLine($"\n telnet localhost {serverPort}");
                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }
        }
Exemple #22
0
        public async Task RunClientAsync(ClientParams args)
        {
            var group                   = new MultithreadEventLoopGroup();
            X509Certificate2 cert       = null;
            string           targetHost = null;

            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                .Group(group)
                .Channel <TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                //.Option(ChannelOption.ConnectTimeout, new TimeSpan(0, 0, 0, 0, args.ConnectTimeout))

                .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    //出栈消息,通过这个handler 在消息顶部加上消息的长度
                    pipeline.AddLast("framing-enc", new LengthFieldPrepender(2));
                    //入栈消息,通过该Handler,解析消息的包长信息,并将正确的消息体发送给下一个处理Handler
                    pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));

                    //心跳检测每10秒进行一次读检测,如果10秒内ChannelRead()方法未被调用则触发一次userEventTrigger()方法.
                    pipeline.AddLast("idleStateHandle", new IdleStateHandler(10, 0, 0));

                    //定义Handler类及名称
                    pipeline.AddLast("NettyClient", new ClientHandler());
                }));

                clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(args.ServerIP, args.ServerPort));

                ClosingArrivedEvent.Reset();

                ClosingArrivedEvent.WaitOne();

                await clientChannel.CloseAsync();
            }
            catch (Exception exp)
            {
                MainWindow.SetText("Client connection failed");
            }
            finally
            {
                //await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
                ReConnectServer();
            }
        }
        /// <summary>
        /// 启动连接
        /// </summary>
        /// <param name="host"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        public async Task Start(string host, int port)
        {
            group      = new MultithreadEventLoopGroup();
            resetEvent = new AutoResetEvent(false);
            X509Certificate2 cert       = null;
            string           targetHost = null;

            if (ClientSettings.IsSsl)
            {
                cert       = new X509Certificate2(Path.Combine("", "dotnetty.com.pfx"), "password");
                targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
            }
            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                .Group(group)
                .Channel <TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    if (cert != null)
                    {
                        pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));
                    }
                    pipeline.AddLast("framing-enc", new LengthFieldPrepender(2));
                    pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));
                    simpleClient = new SimpleClientHandler();
                    pipeline.AddLast("echo", simpleClient);
                    simpleClient.DataNotify += SimpleClient_DataNotity;
                }));
                conTime = DateTime.Now.Ticks;
                Console.WriteLine("客户端连接中");
                clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(host), port));

                isConnected = true;
            }
            catch
            {
                IsUnConnect = true;
                Logger.Singleton.ErrorFormat("客户端无法连接成功,服务端IP{0},端口{1}", host, port);
                if (clientChannel != null)
                {
                    await clientChannel.CloseAsync();
                }
                await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            }
        }
Exemple #24
0
        static RPCClientProxy()
        {
            _bootstrap = new Bootstrap()
                         .Group(new MultithreadEventLoopGroup())
                         .Channel <TcpSocketChannel>()
                         .Option(ChannelOption.TcpNodelay, true)
                         .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                pipeline.AddLast("framing-enc", new LengthFieldPrepender(8));
                pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 8, 0, 8));

                pipeline.AddLast(new ClientHandler(_clientWait));
            }));
        }
Exemple #25
0
 private TcpClient()
 {
     httpClientHandler = new HttpClientHandler();
     group             = new MultithreadEventLoopGroup();
     bootstrap         = new Bootstrap()
                         .Group(group)
                         .Channel <TcpSocketChannel>()
                         .Option(ChannelOption.SoBacklog, 8192)
                         .Handler(new ActionChannelInitializer <IChannel>(channel =>
     {
         IChannelPipeline pipeline = channel.Pipeline;
         pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Unpooled.WrappedBuffer(Encoding.UTF8.GetBytes(delimiter))));
         pipeline.AddLast(new StringEncoder(), new StringDecoder(), new TcpClientHandler());
     }));
 }
Exemple #26
0
        protected override void InitChannel(ISocketChannel channel)
        {
            IChannelPipeline pipeline = channel.Pipeline;

            // Enable stream compression.
            pipeline.AddLast(ZlibCodecFactory.NewZlibEncoder(ZlibWrapper.Gzip));
            pipeline.AddLast(ZlibCodecFactory.NewZlibDecoder(ZlibWrapper.Gzip));

            // Add the number codec first.
            pipeline.AddLast(new BigIntegerDecoder());
            pipeline.AddLast(new BigIntegerEncoder());

            // Add the business logic.
            pipeline.AddLast(new FactorialClientHandler());
        }
Exemple #27
0
        public async Task Start()
        {
            int    port = 6920;
            string p    = ConfigurationManager.AppSettings["NettyPort"];

            if (p == null || "".Equals(p))
            {
                port = int.Parse(p);
            }


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

            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup)           //
                .Channel <TcpServerSocketChannel>()      //
                .Option(ChannelOption.SoBacklog, 100)    //
                .Handler(new LoggingHandler("SRV-LSTN")) //
                .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {                                        //
                    IChannelPipeline pipeline = channel.Pipeline;
                    pipeline.AddLast("frameDecoder", new ProtobufVarint32FrameDecoder());
                    pipeline.AddLast("decoder", new ProtobufDecoder(Message.Parser));
                    pipeline.AddLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
                    pipeline.AddLast("encoder", new ProtobufEncoder());
                    pipeline.AddLast("tcpHandler", new ProtocolHandler());
                }));

                // bootstrap bind port
                IChannel boundChannel = await bootstrap.BindAsync(port);

                //线程阻塞在这

                _mainThread.WaitOne();
                //关闭服务
                await boundChannel.CloseAsync();
            }
            finally
            {
                await Task.WhenAll(
                    bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)),
                    workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)));
            }
        }
Exemple #28
0
        static async Task RunServerAsync()
        {
            var eventListener = new ObservableEventListener();

            eventListener.LogToConsole();
            eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.Verbose);

            var bossGroup   = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();
            X509Certificate2 tlsCertificate = null;

            if (EchoServerSettings.IsSsl)
            {
                tlsCertificate = new X509Certificate2("dotnetty.com.pfx", "password");
            }
            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, 100)
                .Handler(new LoggingHandler(LogLevel.INFO))
                .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    if (tlsCertificate != null)
                    {
                        pipeline.AddLast(TlsHandler.Server(tlsCertificate));
                    }
                    pipeline.AddLast(new LengthFieldPrepender(2));
                    pipeline.AddLast(new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));

                    pipeline.AddLast(new EchoServerHandler());
                }));

                IChannel bootstrapChannel = await bootstrap.BindAsync(EchoServerSettings.Port);

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
                eventListener.Dispose();
            }
        }
Exemple #29
0
        public static void Start()
        {
            SetConsoleLogger();
            //var ports = SaveDataHelper.PortPlantList.Select(l => l.Port).Distinct();
            //主工作线程组,设置为1个线程
            var bossGroup = new MultithreadEventLoopGroup(1);
            //工作线程组,默认为内核数*2的线程数
            var workerGroup = new MultithreadEventLoopGroup();

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

                    //pipeline.AddLast(new IdleStateHandler(5, 0, 0));//第一个参数为读,第二个为写,第三个为读写全部
                    pipeline.AddLast(new LoggingHandler("test"));
                    pipeline.AddLast(new DTUServerHandler());
                }));

                // bootstrap绑定到指定端口的行为 就是服务端启动服务,同样的Serverbootstrap可以bind到多个端口
                //var tasks = ports.Select(bootstrap.BindAsync).ToArray();

                var tasks = bootstrap.BindAsync(8007);
                Task.WaitAll(tasks);
                var test = tasks.Result;
                Console.ReadLine();
                test.CloseAsync();
                //channel = tasks.Select(s => s.Result).ToList();
            }
            catch (Exception ex)
            {
                LogUtil.Error("连接错误:" + ex.Message);
            }
            //finally
            //{
            //    //关闭线程组,先打开的后关闭
            //    bossGroup.ShutdownGracefullyAsync();
            //    workerGroup.ShutdownGracefullyAsync();
            //}
        }
 private void InitBootstrap()
 {
     SocketBootstrap.Group(WorkGroup)
     .Channel <TcpSocketChannel>()
     .Option(ChannelOption.TcpNodelay, true)
     .Option(ChannelOption.SoKeepalive, true)
     .Option(ChannelOption.SoTimeout, 5)
     .Option(ChannelOption.ConnectTimeout, TimeSpan.FromSeconds(5))
     .Handler(new ActionChannelInitializer <ISocketChannel>(channel => {
         IChannelPipeline pipeline = channel.Pipeline;
         pipeline.AddLast("idleStateHandler", new IdleStateHandler(0, 5, 0));
         pipeline.AddLast("customEncoder", new CustomProtocolEncoder(Encoding.UTF8));
         pipeline.AddLast("customDecoder", new CustomProtocolDecoder(Encoding.UTF8));
         pipeline.AddLast("tcpHandler", handler);
     }));
 }