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 DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                    pipeline.AddLast(new StringEncoder(), new StringDecoder(), new ClientHandler());
                }));

                IPAddress ip = IPAddress.Parse("127.0.0.1");
                IChannel  bootstrapChannel = await bootstrap.ConnectAsync(new IPEndPoint(ip, 4242));

                for (; ;)
                {
                    string line = Console.ReadLine();
                    if (string.IsNullOrEmpty(line))
                    {
                        continue;
                    }

                    try
                    {
                        await bootstrapChannel.WriteAndFlushAsync(line + "\r\n");
                    }

                    catch
                    {
                        Console.WriteLine("Deconnection...");
                        await bootstrapChannel.CloseAsync();

                        break;
                    }
                    if (string.Equals(line, "/leave", StringComparison.OrdinalIgnoreCase))
                    {
                        await bootstrapChannel.CloseAsync();

                        break;
                    }
                }

                await bootstrapChannel.CloseAsync();
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Serveur introuvable");
            }
            finally
            {
                group.ShutdownGracefullyAsync().Wait(1000);
            }
        }
Exemple #2
0
        static async Task RunServerAsync()
        {
            var bossGroup   = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();

            var STRING_ENCODER = new StringEncoder();
            var STRING_DECODER = new StringDecoder();
            var SERVER_HANDLER = new ChatServerHandler();

            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;
                    pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                    pipeline.AddLast(STRING_ENCODER, STRING_DECODER, SERVER_HANDLER);
                }));

                IChannel bootstrapChannel = await bootstrap.BindAsync(8080);

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }
        }
        public async Task Connect(string serverAddress)
        {
            try
            {
                group = new MultithreadEventLoopGroup();
                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 DelimiterBasedFrameDecoder(133680, Delimiters.LineDelimiter()));
                    pipeline.AddLast(new StringEncoder(), new StringDecoder(), ClientHandler);
                }));

                bootstrapChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(serverAddress), 9527));
            }
            catch
            {
                group.ShutdownGracefullyAsync().Wait(1000);
            }
        }
Exemple #4
0
        public async void Start()
        {
            bossGroup   = new MultithreadEventLoopGroup(1);
            workerGroup = new MultithreadEventLoopGroup();

            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;

                    pipeline.AddLast(new DelimiterBasedFrameDecoder(133680, Delimiters.LineDelimiter()));
                    pipeline.AddLast(STRING_ENCODER, STRING_DECODER, new UpdaterServerHandler());
                }));

                bootstrapChannel = await bootstrap.BindAsync(9527);

                Console.WriteLine("服务已启动...");
                LoggerHelper.Info("服务已启动...");
            }
            catch (Exception ex)
            {
                Console.WriteLine("服务启动异常:{0}", ex.StackTrace);
                LoggerHelper.Error("服务启动异常", ex);
            }
        }
Exemple #5
0
        static async Task RunClientAsync(string ip, int port)
        {
            var group = new MultithreadEventLoopGroup();

            string targetHost = null;

            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 DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                    pipeline.AddLast(new StringEncoder(), new StringDecoder(), handler);
                }));

                IChannel bootstrapChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(ip), port));

                for (;;)
                {
                    Console.Write("$> ");
                    var line = Console.ReadLine();
                    if (string.IsNullOrEmpty(line))
                    {
                        continue;
                    }

                    try
                    {
                        var response = GameHandler.HandleClientCmd(handler.GetEventHandler(), line);
                        if (response != null)
                        {
                            var serObj = SerializeHandler.SerializeObj(response);
                            await bootstrapChannel.WriteAndFlushAsync(serObj + "\r\n");
                        }
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine(e.Message);
                    }
                    if (string.Equals(line, "bye", StringComparison.OrdinalIgnoreCase))
                    {
                        await bootstrapChannel.CloseAsync();

                        break;
                    }
                }

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

            var stringEncoder = new StringEncoder();
            var stringDecoder = new StringDecoder();
            var serverHandler = new ServerHandler(GameCore);

            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 =>
                {
                    var pipeline = channel.Pipeline;

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

                var bootstrapChannel = await bootstrap.BindAsync(port);

                GameCore.RunContainers();
                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }
        }
Exemple #7
0
        static async Task RunClientAsync()
        {
            var HOST  = IPAddress.Parse("127.0.0.1");
            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 DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                    pipeline.AddLast(new StringEncoder(), new StringDecoder(), new ChatClientHandler());
                }));

                IChannel bootstrapChannel = await bootstrap.ConnectAsync(new IPEndPoint(HOST, 8080));

                ProtocolJson pj = new ProtocolJson();

                for (;;)
                {
                    string line = Console.ReadLine();

                    pj.message     = line;
                    pj.messageDate = DateTime.Now;
                    string Json = JsonConvert.SerializeObject(pj, Formatting.None);

                    if (string.IsNullOrEmpty(line))
                    {
                        continue;
                    }
                    try
                    {
                        await bootstrapChannel.WriteAndFlushAsync(Json + "\r\n");

                        //await bootstrapChannel.WriteAndFlushAsync(line + "\r\n");
                    }
                    catch
                    {
                    }
                    if (string.Equals(line, "bye", StringComparison.OrdinalIgnoreCase))
                    {
                        await bootstrapChannel.CloseAsync();

                        break;
                    }
                }

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                group.ShutdownGracefullyAsync().Wait(1000);
            }
        }
 protected override void InitChannel(ISocketChannel channel)
 {
     channel.Pipeline
     // Add the text line codec combination first.
     .AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()))
     .AddLast(Decoder)
     .AddLast(Encoder)
     // Add business logic.
     .AddLast(ClientHandler);
 }
Exemple #9
0
 protected override void InitChannel(ISocketChannel channel)
 {
     channel.Pipeline
     // Add the text line codec combination first.
     .AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()))
     // The encoder and decoder are static as these are sharable.
     .AddLast(Decoder)
     .AddLast(Encoder)
     // Add the business logic.
     .AddLast(ServerHandler);
 }
Exemple #10
0
        static async Task RunServerAsync()
        {
            var logLevel = LogLevel.INFO;

            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 StringDecoder();
            var helloWorldServerHandler = new HelloWorldServerHandler();

            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;

                    // handler evaluation order is 1, 2, 3, 4, 5 for inbound data and 5, 4, 3, 2, 1 for outbound

                    // The DelimiterBasedFrameDecoder splits the data stream into frames (individual messages e.g. strings ) and do not allow requests longer than n chars.
                    // It is required to use a frame decoder suchs as DelimiterBasedFrameDecoder or LineBasedFrameDecoder before the StringDecoder.
                    pipeline.AddLast("1", new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                    pipeline.AddLast("2", encoder);
                    pipeline.AddLast("3", decoder);
                    pipeline.AddLast("4", new CountCharsServerHandler());
                    //pipeline.AddLast("4½", new HasUpperCharsServerHandler());
                    pipeline.AddLast("5", helloWorldServerHandler);
                }));

                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 #11
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 DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                    pipeline.AddLast(new StringEncoder(), new StringDecoder(), new TelnetClientHandler());
                }));

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

                for (; ;)
                {
                    string line = Console.ReadLine();
                    if (string.IsNullOrEmpty(line))
                    {
                        continue;
                    }

                    try
                    {
                        await bootstrapChannel.WriteAndFlushAsync(line + "\r\n");
                    }
                    catch
                    {
                        // ignored
                    }
                    if (string.Equals(line, "bye", StringComparison.OrdinalIgnoreCase))
                    {
                        await bootstrapChannel.CloseAsync();

                        break;
                    }
                }

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                group.ShutdownGracefullyAsync().Wait(1000);
            }
        }
        public static IServerBootstrapWrapper AddSecureChatHandler <TChannelHandler>(this IServerBootstrapWrapper wrapper,
                                                                                     X509Certificate2 tlsCertificate, TChannelHandler secureChatHandler)
            where TChannelHandler : IChannelHandler
        {
            wrapper.NotNull(nameof(wrapper));

            return(wrapper.AddChannelHandler <IChannel>(tlsCertificate, pipeline =>
            {
                pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                pipeline.AddLast(new StringEncoder());
                pipeline.AddLast(new StringDecoder());
                pipeline.AddLast(secureChatHandler);
            }));
        }
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());
            }
        }
        public static IBootstrapWrapper AddTelnetHandler <TChannelHandler>(this IBootstrapWrapper wrapper,
                                                                           X509Certificate2 tlsCertificate, TChannelHandler channelHandler)
            where TChannelHandler : IChannelHandler
        {
            wrapper.NotNull(nameof(wrapper));

            return(wrapper.AddChannelHandlerAsync <ISocketChannel>(tlsCertificate, pipeline =>
            {
                pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                pipeline.AddLast(new StringEncoder());
                pipeline.AddLast(new StringDecoder());
                pipeline.AddLast(channelHandler);
            }));
        }
Exemple #15
0
        public static async Task RunServerAsync()
        {
//            ServerHelper.SetConsoleLogger();

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

            var STRING_ENCODER = new StringEncoder();
            var STRING_DECODER = new StringDecoder();
            var SERVER_HANDLER = new TelnetServerHandler();

            X509Certificate2 tlsCertificate = null;

            if (ServerSettings.IsSsl)
            {
                tlsCertificate = new X509Certificate2(Path.Combine(KernelHelper.ProcessDirectory, "bittymud.pfx"), "password");
            }
            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, 100)
                .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    if (tlsCertificate != null)
                    {
                        pipeline.AddLast(TlsHandler.Server(tlsCertificate));
                    }

                    pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                    pipeline.AddLast(STRING_ENCODER, STRING_DECODER, SERVER_HANDLER);
                }));

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

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }
        }
Exemple #16
0
        private async void NettyServer_Load(object sender, EventArgs e)
        {
            var bootstrap = new ServerBootstrap();

            bootstrap
            .Group(boss, worker)
            .Channel <TcpServerSocketChannel>()
            //.Option(ChannelOption.SoKeepalive, true)
            .ChildHandler(new ActionChannelInitializer <ISocketChannel>(c =>
            {
                var line = c.Pipeline;
                line.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                line.AddLast(new StringEncoder(), new StringDecoder());
                line.AddLast(new ChatServerHandler(this));
            }));
            this.channel = await bootstrap.BindAsync(IPAddress.Parse("127.0.0.1"), 9900);
        }
Exemple #17
0
        private async void NettyClient_Load(object sender, EventArgs e)
        {
            var bootstrap = new Bootstrap();

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

                line.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                line.AddLast(new StringEncoder(), new StringDecoder());
                line.AddLast(new ChatClientHandler(this));
            }));

            this.channel = await bootstrap.ConnectAsync(IPAddress.Parse("127.0.0.1"), 8080);
        }
Exemple #18
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 DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                    pipeline.AddLast(new StringEncoder(), new StringDecoder(), new ProxyClientHandler());
                }));
                bootstrapChannel = await bootstrap.ConnectAsync(IPAddress.Parse(ConfigHelper.GetValue <string>("server")), ConfigHelper.GetValue <int>("port"));

                Console.WriteLine("Success Connect");
                for (; ;)
                {
                    string line = Console.ReadLine();
                    if (string.IsNullOrEmpty(line))
                    {
                        continue;
                    }
                    if (string.Equals(line, "bye", StringComparison.OrdinalIgnoreCase))
                    {
                        await bootstrapChannel.CloseAsync();

                        break;
                    }
                }

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                group.ShutdownGracefullyAsync().Wait(1000);
            }
        }
Exemple #19
0
        public void MultipleLines()
        {
            EmbeddedChannel ch = new EmbeddedChannel(new DelimiterBasedFrameDecoder(8192, false,
                                                                                    Delimiters.LineDelimiter()));

            ch.WriteInbound(Unpooled.CopiedBuffer("TestLine\r\ng\r\n", Encoding.UTF8));

            var buf = ch.ReadInbound <IByteBuffer>();

            Assert.Equal("TestLine\r\n", buf.ToString(Encoding.UTF8));

            var buf2 = ch.ReadInbound <IByteBuffer>();

            Assert.Equal("g\r\n", buf2.ToString(Encoding.UTF8));
            Assert.Null(ch.ReadInbound <IByteBuffer>());
            ch.Finish();

            buf.Release();
            buf2.Release();
        }
Exemple #20
0
        public void Decode()
        {
            EmbeddedChannel ch = new EmbeddedChannel(
                new DelimiterBasedFrameDecoder(8192, true, Delimiters.LineDelimiter()));

            ch.WriteInbound(Unpooled.CopiedBuffer("first\r\nsecond\nthird", Encoding.ASCII));

            var buf = ch.ReadInbound <IByteBuffer>();

            Assert.Equal("first", buf.ToString(Encoding.ASCII));

            var buf2 = ch.ReadInbound <IByteBuffer>();

            Assert.Equal("second", buf2.ToString(Encoding.ASCII));
            Assert.Null(ch.ReadInbound <IByteBuffer>());
            ch.Finish();

            ReferenceCountUtil.Release(ch.ReadInbound <IByteBuffer>());

            buf.Release();
            buf2.Release();
        }
Exemple #21
0
        public static async Task RunServerAsync()
        {
            //在控制台命令中启用日志
            ExampleHelper.SetConsoleLogger();
            //多线程事件循环组,创建一个新实例,老板组
            var bossGroup = new MultithreadEventLoopGroup(1);
            //多线程事件循环组,创建一个新实例,工作组
            var workerGroup = new MultithreadEventLoopGroup();

            //字符串编码
            var STRING_ENCODER = new StringEncoder();
            //字符串解码
            var STRING_DECODER = new StringDecoder();
            //安全聊天服务器处理程序
            var SERVER_HANDLER = new SecureChatServerHandler();

            X509Certificate2 tlsCertificate = null;

            if (ServerSettings.IsSsl)
            {
                // 创建 X.509 证书
                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用于服务请求 “信息”日志级别。
                .Handler(new LoggingHandler(LogLevel.INFO))
                //设置{@链接channelhandler }这是用来服务请求{@链接通道}的。
                .ChildHandler(
                    new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    if (tlsCertificate != null)
                    {
                        //添加协议到最后
                        pipeline.AddLast(TlsHandler.Server(tlsCertificate));
                    }
                    //添加基于行分隔符的帧解码器到最后
                    pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                    pipeline.AddLast(STRING_ENCODER, STRING_DECODER, SERVER_HANDLER);
                }));
                // 创建异步通道并绑定异步端口
                IChannel bootstrapChannel = await bootstrap.BindAsync(ServerSettings.Port);

                Console.ReadLine();
                //关闭异步
                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                // 等待提供的所有 System.Threading.Tasks.Task 对象完成执行过程
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }
        }
        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(new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));
                    }

                    pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
                    pipeline.AddLast(new StringEncoder(), new StringDecoder(), new SecureChatClientHandler());
                }));

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

                for (;;)
                {
                    string line = Console.ReadLine();
                    if (string.IsNullOrEmpty(line))
                    {
                        continue;
                    }

                    try
                    {
                        await bootstrapChannel.WriteAndFlushAsync(line + "\r\n");
                    }
                    catch
                    {
                    }
                    if (string.Equals(line, "bye", StringComparison.OrdinalIgnoreCase))
                    {
                        await bootstrapChannel.CloseAsync();

                        break;
                    }
                }

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                group.ShutdownGracefullyAsync().Wait(1000);
            }
        }
        private static async Task TestStringEcho0(ServerBootstrap sb, Bootstrap cb, bool autoRead, ITestOutputHelper output)
        {
            sb.ChildOption(ChannelOption.AutoRead, autoRead);
            cb.Option(ChannelOption.AutoRead, autoRead);

            IPromise          serverDonePromise = new DefaultPromise();
            IPromise          clientDonePromise = new DefaultPromise();
            StringEchoHandler sh = new StringEchoHandler(autoRead, serverDonePromise, output);
            StringEchoHandler ch = new StringEchoHandler(autoRead, clientDonePromise, output);

            sb.ChildHandler(new ActionChannelInitializer <IChannel>(sch =>
            {
                sch.Pipeline.AddLast("framer", new DelimiterBasedFrameDecoder(512, Delimiters.LineDelimiter()));
                sch.Pipeline.AddLast("decoder", new StringDecoder(Encoding.ASCII));
                sch.Pipeline.AddBefore("decoder", "encoder", new StringEncoder(Encoding.ASCII));
                sch.Pipeline.AddAfter("decoder", "handler", sh);
            }));

            cb.Handler(new ActionChannelInitializer <IChannel>(sch =>
            {
                sch.Pipeline.AddLast("framer", new DelimiterBasedFrameDecoder(512, Delimiters.LineDelimiter()));
                sch.Pipeline.AddLast("decoder", new StringDecoder(Encoding.ASCII));
                sch.Pipeline.AddBefore("decoder", "encoder", new StringEncoder(Encoding.ASCII));
                sch.Pipeline.AddAfter("decoder", "handler", ch);
            }));

            IChannel sc = await sb.BindAsync();

            IChannel cc = await cb.ConnectAsync(sc.LocalAddress);

            for (int i = 0; i < s_data.Length; i++)
            {
                string element   = s_data[i];
                string delimiter = s_random.Next(0, 1) == 1 ? "\r\n" : "\n";
                await cc.WriteAndFlushAsync(element + delimiter);
            }

            await ch._donePromise.Task;
            await sh._donePromise.Task;
            await sh._channel.CloseAsync();

            await ch._channel.CloseAsync();

            await sc.CloseAsync();

            if (sh._exception.Value != null && !(sh._exception.Value is SocketException || (sh._exception.Value is ChannelException chexc && chexc.InnerException is OperationException) || sh._exception.Value is OperationException))
            {
                throw sh._exception.Value;
            }
            if (ch._exception.Value != null && !(ch._exception.Value is SocketException || (sh._exception.Value is ChannelException chexc1 && chexc1.InnerException is OperationException) || sh._exception.Value is OperationException))
            {
                throw ch._exception.Value;
            }
            if (sh._exception.Value != null)
            {
                throw sh._exception.Value;
            }
            if (ch._exception.Value != null)
            {
                throw ch._exception.Value;
            }
        }
Exemple #24
0
 public TenantOneContext(TenantInfo tenantInfo, IChannelHandlerContext channelContext, ISettingsProvider settingsProvider) :
     base(settingsProvider, tenantInfo, channelContext, new DelimiterBasedFrameDecoder(settingsProvider.GetIntegerSetting("MaxInboundMessageSize", 256 * 1024), true, Delimiters.LineDelimiter()))
 {
     this.settingsProvider = settingsProvider;
 }
 public DelayedTenancyContext(IChannelHandlerContext context, ISettingsProvider settingsProvider)
     : base(settingsProvider, null, context, new DelimiterBasedFrameDecoder(settingsProvider.GetIntegerSetting("MaxInboundMessageSize", 256 * 1024), true, Delimiters.LineDelimiter()))
 {
     this.settingsProvider = settingsProvider;
 }