protected AbstractChannelHandlerContext(IChannelPipeline pipeline, IChannelHandlerInvoker invoker,
            string name, PropagationDirections skipPropagationDirections)
        {
            Contract.Requires(pipeline != null);
            Contract.Requires(name != null);

            this.Channel = pipeline.Channel();
            this.invoker = invoker;
            this.skipPropagationFlags = skipPropagationDirections;
            this.Name = name;
        }
Exemplo n.º 2
0
        public Task HandshakeAsync(IChannel channel, IHttpRequest req, HttpHeaders responseHeaders)
        {
            if (req is IFullHttpRequest request)
            {
                return(this.HandshakeAsync(channel, request, responseHeaders));
            }
            if (Logger.IsDebugEnabled)
            {
                Logger.DebugFormat("{} WebSocket version {} server handshake", channel, this.version);
            }
            IChannelPipeline       p   = channel.Pipeline;
            IChannelHandlerContext ctx = p.Context <HttpRequestDecoder>();

            if (ctx == null)
            {
                // this means the user use a HttpServerCodec
                ctx = p.Context <HttpServerCodec>();
                if (ctx == null)
                {
                    return(TaskEx.FromException(new InvalidOperationException("No HttpDecoder and no HttpServerCodec in the pipeline")));
                }
            }

            // Add aggregator and ensure we feed the HttpRequest so it is aggregated. A limit o 8192 should be more then
            // enough for the websockets handshake payload.
            //
            // TODO: Make handshake work without HttpObjectAggregator at all.
            string aggregatorName = "httpAggregator";

            p.AddAfter(ctx.Name, aggregatorName, new HttpObjectAggregator(8192));
            var completion = new TaskCompletionSource();

            p.AddAfter(aggregatorName, "handshaker", new Handshaker(this, channel, responseHeaders, completion));
            try
            {
                ctx.FireChannelRead(ReferenceCountUtil.Retain(req));
            }
            catch (Exception cause)
            {
                completion.TrySetException(cause);
            }
            return(completion.Task);
        }
Exemplo n.º 3
0
        public async override Task <ITcpSocketClient> BuildAsync()
        {
            TcpSocketClient tcpClient = new TcpSocketClient(_ip, _port, _event);

            var clientChannel = await new Bootstrap()
                                .Group(new MultithreadEventLoopGroup())
                                .Channel <TcpSocketChannel>()
                                .Option(ChannelOption.TcpNodelay, true)
                                .Handler(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                _setEncoder?.Invoke(pipeline);
                pipeline.AddLast(new CommonChannelHandler(tcpClient));
            })).ConnectAsync($"{_ip}:{_port}".ToIPEndPoint());

            tcpClient.SetChannel(clientChannel);

            return(await Task.FromResult(tcpClient));
        }
            public Context()
            {
                _channel = Substitute.For <IChannel>();
                _channelHandlerContext = Substitute.For <IChannelHandlerContext>();
                _pipeline = Substitute.For <IChannelPipeline>();
                _channelHandlerContext.Channel.Returns(_channel);
                _channel.Pipeline.Returns(_pipeline);
                _pipeline.Get <ZeroPacketSplitter>().Returns(new ZeroPacketSplitter(LimboLogs.Instance));
                _packetSender = Substitute.For <IPacketSender>();
                _syncServer   = Substitute.For <ISyncServer>();
                _syncServer   = Substitute.For <ISyncServer>();
                _syncServer.Genesis.Returns(Build.A.Block.Genesis.TestObject.Header);
                _syncServer.Head.Returns(Build.A.BlockHeader.TestObject);
                _txPool       = Substitute.For <ITxPool>();
                _discoveryApp = Substitute.For <IDiscoveryApp>();
                _serializer   = new MessageSerializationService();
                _localPeer    = Substitute.For <IRlpxPeer>();
                _localPeer.LocalPort.Returns(_localPort);
                _localPeer.LocalNodeId.Returns(TestItem.PublicKeyA);
                _nodeStatsManager = new NodeStatsManager(new StatsConfig(), LimboLogs.Instance);
                _blockTree        = Substitute.For <IBlockTree>();
                _blockTree.ChainId.Returns(1);
                _blockTree.Genesis.Returns(Build.A.Block.Genesis.TestObject.Header);
                _protocolValidator = new ProtocolValidator(_nodeStatsManager, _blockTree, LimboLogs.Instance);
                _peerStorage       = Substitute.For <INetworkStorage>();
                _syncPeerPool      = Substitute.For <ISyncPeerPool>();
                _manager           = new ProtocolsManager(
                    _syncPeerPool,
                    _syncServer,
                    _txPool,
                    _discoveryApp,
                    _serializer,
                    _localPeer,
                    _nodeStatsManager,
                    _protocolValidator,
                    _peerStorage,
                    MainnetSpecProvider.Instance,
                    LimboLogs.Instance);

                _serializer.Register(new HelloMessageSerializer());
                _serializer.Register(new StatusMessageSerializer());
                _serializer.Register(new DisconnectMessageSerializer());
            }
Exemplo n.º 5
0
        public async Task WebIMServer()
        {
            IEventLoopGroup bossGroup   = new MultithreadEventLoopGroup(1);
            IEventLoopGroup workerGroup = new MultithreadEventLoopGroup();

            var isSsl = Convert.ToBoolean(_configuration["SSL:IsSsl"]);

            X509Certificate2 tlsCertificate = null;

            if (isSsl)
            {
                var path     = _configuration["SSL:Path"];
                var password = _configuration["SSL:Password"];

                tlsCertificate = string.IsNullOrWhiteSpace(password) ? new X509Certificate2(path) : new X509Certificate2(path, password);
            }

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

                if (isSsl)
                {
                    pipeline.AddLast(TlsHandler.Server(tlsCertificate));
                }

                pipeline
                .AddLast(new IdleStateHandler(_heartBeatTime, 0, 0))
                .AddLast(new HttpServerCodec())
                .AddLast(new HttpObjectAggregator(65536))
                .AddLast(new WebSocketDecoder())
                .AddLast(new ProtobufDecoder(CatMessage.Parser))
                .AddLast(new WebSocketEncoder())
                .AddLast(new WebSocketServerProtocolHandler("/ws", null, true))
                .AddLast(new ServerHandler(_logger, _messageController));
            }));

            await bootstrap.BindAsync(_port);
        }
Exemplo n.º 6
0
        static async Task RunServerAsync()
        {
            IEventLoopGroup bossGroup   = new MultithreadEventLoopGroup(1);
            IEventLoopGroup workerGroup = new MultithreadEventLoopGroup();

            Console.WriteLine("NLog server starting...");

            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;
                    pipeline.AddLast(new LoggingHandler("SRV-CONN"));
                    pipeline.AddLast("framing-enc", new LengthFieldPrepender(2));
                    pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));

                    pipeline.AddLast("nlog", new NLogHandler());
                }));

                IChannel boundChannel = await bootstrap.BindAsync(port);

                Console.WriteLine($"listening on port : {port}");
                while (Console.ReadLine() != "exit")
                {
                    Console.WriteLine("type 'exit' to close this app.");
                }

                await boundChannel.CloseAsync();
            }
            finally
            {
                await Task.WhenAll(
                    bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)),
                    workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)));
            }
        }
Exemplo n.º 7
0
        async Task RunServerAsync()
        {
            if (commSetting.useConsoleLoger)
            {
                commSetting.SetConsoleLogger();
            }
            bossGroup   = new MultithreadEventLoopGroup(1);
            workerGroup = new MultithreadEventLoopGroup();

            var SERVER_HANDLER = new RpcServerHandler(this);

            X509Certificate2 tlsCertificate = null;

            if (useSSl)
            {
                tlsCertificate = new X509Certificate2(Path.Combine(commSetting.ProcessDirectory, sslFile), sslPassword);
            }
            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap
                .Group(bossGroup, workerGroup)
                .Channel <CustTcpServerSocketChannel>()
                .Option(ChannelOption.SoBacklog, backLength)
                // .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 IdleStateHandler(commSetting.IdleStateTime, 0, 0));
                    pipeline.AddLast(new FastPacketDecode(commSetting.MAX_FRAME_LENGTH, commSetting.LENGTH_FIELD_OFFSET, commSetting.LENGTH_FIELD_LENGTH, commSetting.LENGTH_ADJUSTMENT, commSetting.INITIAL_BYTES_TO_STRIP, false));
                    pipeline.AddLast(new FastPacketEncoder(), SERVER_HANDLER);
                }));

                rpcServerChannel = AsyncHelpers.RunSync <IChannel>(() => bootstrap.BindAsync(port));
            }
            finally
            {
            }
        }
Exemplo n.º 8
0
        /// <summary>
        ///     Write messages to the inbound of this <see cref="IChannel" />
        /// </summary>
        /// <param name="msgs">The messages to be written.</param>
        /// <returns><c>true</c> if the write operation did add something to the inbound buffer</returns>
        public bool WriteInbound(params object[] msgs)
        {
            this.EnsureOpen();
            if (msgs.Length == 0)
            {
                return(IsNotEmpty(this.inboundMessages));
            }

            IChannelPipeline p = this.Pipeline;

            foreach (object m in msgs)
            {
                p.FireChannelRead(m);
            }
            p.FireChannelReadComplete();
            this.RunPendingTasks();
            this.CheckException();
            return(IsNotEmpty(this.inboundMessages));
        }
Exemplo n.º 9
0
        public static IServiceHostClientBuilder UseRpcForTransfer(this IServiceHostClientBuilder serviceHostBuilder)
        {
            serviceHostBuilder.AddInitializer(container =>
            {
                ITransportClientFactory factory = container.Resolve <ITransportClientFactory>();
                ILogger logger         = container.Resolve <ILogger>();
                ISerializer serializer = container.Resolve <ISerializer>();
                Bootstrap bootstrap    = new Bootstrap();

                logger.Info($"启动rpc客户端");

                bootstrap
                .Group(new MultithreadEventLoopGroup())
                .Channel <TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;
                    pipeline.AddLast(new LengthFieldPrepender(4));
                    pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4));
                    pipeline.AddLast(new ReadClientMessageChannelHandler(serializer));
                    pipeline.AddLast(new RpcClientHandler(factory));
                }));
                AttributeKey <IClientSender> clientSenderKey     = AttributeKey <IClientSender> .ValueOf(typeof(DefaultTransportClientFactory), nameof(IClientSender));
                AttributeKey <IClientListener> clientListenerKey = AttributeKey <IClientListener> .ValueOf(typeof(DefaultTransportClientFactory), nameof(IClientListener));

                factory.ClientCreatorDelegate += (ServerAddress address, ref ITransportClient client) =>
                {
                    if (client == null && address.ServerFlag == ServerFlag.Rpc)
                    {
                        EndPoint ep                = address.CreateEndPoint();
                        IChannel channel           = bootstrap.ConnectAsync(ep).Result;
                        RpcClientListener listener = new RpcClientListener();
                        channel.GetAttribute(clientListenerKey).Set(listener);
                        RpcClientSender sender = new RpcClientSender(channel, serializer);
                        channel.GetAttribute(clientSenderKey).Set(sender);
                        client = new DefaultTransportClient(listener, sender, serializer, logger);
                    }
                };
            });

            return(serviceHostBuilder);
        }
Exemplo n.º 10
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            bossGroup             = new DispatcherEventLoopGroup();
            workerGroup           = new WorkerEventLoopGroup(bossGroup, configuration.EventLoopCount);
            serverBufferAllocator = new PooledByteBufferAllocator();
            //serverBufferAllocator = new UnpooledByteBufferAllocator();
            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
            .Option(ChannelOption.SoBacklog, configuration.SoBacklog)
            .ChildOption(ChannelOption.Allocator, serverBufferAllocator)
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                using (var scope = serviceProvider.CreateScope())
                {
                    channel.Pipeline.AddLast("jt808TcpBuffer", new DelimiterBasedFrameDecoder(int.MaxValue,
                                                                                              Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.BeginFlag }),
                                                                                              Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.EndFlag })));
                    channel.Pipeline.AddLast("jt808TcpDecode", scope.ServiceProvider.GetRequiredService <JT808TcpDecoder>());
                    channel.Pipeline.AddLast("jt808TcpEncode", scope.ServiceProvider.GetRequiredService <JT808TcpEncoder>());
                    channel.Pipeline.AddLast("systemIdleState", new IdleStateHandler(
                                                 configuration.ReaderIdleTimeSeconds,
                                                 configuration.WriterIdleTimeSeconds,
                                                 configuration.AllIdleTimeSeconds));
                    channel.Pipeline.AddLast("jt808TcpConnection", scope.ServiceProvider.GetRequiredService <JT808TcpConnectionHandler>());
                    channel.Pipeline.AddLast("jt808TcpService", scope.ServiceProvider.GetRequiredService <JT808TcpServerHandler>());
                }
            }));
            logger.LogInformation($"JT808 TCP Server start at {IPAddress.Any}:{configuration.TcpPort}.");
            return(bootstrap.BindAsync(configuration.TcpPort)
                   .ContinueWith(i => bootstrapChannel = i.Result));
        }
Exemplo n.º 11
0
        static async Task RunServer()
        {
            var eventListener = new ObservableEventListener();

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

            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(LogLevel.INFO))
                .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    if (EchoServerSettings.IsSsl)
                    {
                        pipeline.AddLast(TlsHandler.Server(new X509Certificate2("dotnetty.com.pfx", "password")));
                    }

                    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();
            }
        }
Exemplo n.º 12
0
        protected override void Init(IChannel channel)
        {
            foreach (ChannelOptionValue e in this.Options)
            {
                try
                {
                    if (!e.Set(channel.Configuration))
                    {
                        Logger.Warn("Unknown channel option: " + e);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Warn("Failed to set a channel option: " + channel, ex);
                }
            }

            foreach (AttributeValue e in this.Attributes)
            {
                e.Set(channel);
            }

            IChannelPipeline p = channel.Pipeline;
            IChannelHandler  channelHandler = this.Handler();

            if (channelHandler != null)
            {
                p.AddLast((string)null, channelHandler);
            }

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

            ChannelOptionValue[] currentChildOptions = this.childOptions.Values.ToArray();
            AttributeValue[]     currentChildAttrs   = this.childAttrs.Values.ToArray();

            p.AddLast(new ActionChannelInitializer <IChannel>(ch =>
            {
                ch.Pipeline.AddLast(new ServerBootstrapAcceptor(currentChildGroup, currentChildHandler,
                                                                currentChildOptions, currentChildAttrs));
            }));
        }
Exemplo n.º 13
0
        static async Task Main(string[] args)
        {
            ExampleHelper.SetConsoleLogger();

            var bossGroup   = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();
            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 DiscardServerHandler());
                }));

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

                Console.ReadLine();

                await bootstrapChannel.CloseAsync();
            }
            finally
            {
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }
        }
Exemplo n.º 14
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);
            }
        }
        private void InitDotNetty()
        {
            group     = new MultithreadEventLoopGroup();
            bootstrap = new Bootstrap();
            bootstrap
            .Group(group)
            .Channel <TcpSocketChannel>()
            .Option(ChannelOption.TcpNodelay, true)
            .Option(ChannelOption.ConnectTimeout, TimeSpan.FromSeconds(3))
            .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                // Tcp粘包处理,添加一个LengthFieldBasedFrameDecoder解码器,它会在解码时按照消息头的长度来进行解码。
                pipeline.AddLast("frameDecoder", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 4, 0, 4));
                // MessagePack解码器,消息进来后先由frameDecoder处理,再给msgPackDecoder处理
                pipeline.AddLast("msgPackDecoder", new MessagePackDecoder());
                // Tcp粘包处理,添加一个
                // LengthFieldPrepender编码器,它会在ByteBuf之前增加4个字节的字段,用于记录消息长度。
                pipeline.AddLast("frameEncoder", new LengthFieldPrepender(4));
                // MessagePack编码器,消息发出之前先由frameEncoder处理,再给msgPackEncoder处理
                pipeline.AddLast("msgPackEncoder", new MessagePackEncoder());

                // IdleStateHandler 心跳
                //客户端为写IDLE
                pipeline.AddLast(new IdleStateHandler(0, 0, 0));

                // 消息处理handler
                if (DotNettyClientHandler != null)
                {
                    DotNettyClientHandler.ReceiveEventFromClientEvent -= ReceiveMessage;
                    DotNettyClientHandler.ReconnectServer             -= () => ConnectToServer().Wait();
                    DotNettyClientHandler.RecordLogEvent -= this.RecordLogEvent;
                }
                DotNettyClientHandler = new EchoClientHandler();
                DotNettyClientHandler.ReceiveEventFromClientEvent += ReceiveMessage;
                DotNettyClientHandler.ReconnectServer             += () => ConnectToServer().Wait();
                DotNettyClientHandler.RecordLogEvent += this.RecordLogEvent;
                pipeline.AddLast("handler", DotNettyClientHandler);
            }));
            bootstrap.RemoteAddress(new IPEndPoint(IPAddress.Parse(this.ServerIP), this.ServerPort));
            CheckConnectServer();
        }
Exemplo n.º 16
0
        static async Task RunClient()
        {
            var eventListener = new ObservableEventListener();

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

            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;

                    if (EchoClientSettings.IsSsl)
                    {
                        var cert          = new X509Certificate2("dotnetty.com.pfx", "password");
                        string targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
                        pipeline.AddLast(TlsHandler.Client(targetHost, null, (sender, certificate, chain, errors) => true));
                    }

                    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();
            }
        }
Exemplo n.º 17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public async void Connect(string ip, int port)
        {
            group = new MultithreadEventLoopGroup();

            X509Certificate2 cert       = null;
            string           targetHost = null;

            if (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("framing-enc", new LengthFieldPrepender(4));
                    pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(Int32.MaxValue, 0, 4, 0, 4));
                    mChannelHandler = new ClientChannelHandler(this);
                    mChannelHandler.DataArrivedEvent += ProcessData;
                    pipeline.AddLast(mChannelHandler);
                }));

                clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(ip), port));
            }
            catch
            {
                Close();
                NeedReConnected = true;
            }
        }
Exemplo n.º 18
0
        /// <summary>运行
        /// </summary>
        public override async ValueTask ConnectAsync()
        {
            if (_channel != null && _channel.Registered)
            {
                Logger.LogInformation($"Client is running! Don't run again! ChannelId:{_channel.Id.AsLongText()}");
                return;
            }

            try
            {
                _group     = new MultithreadEventLoopGroup();
                _bootStrap = new Bootstrap();
                _bootStrap
                .Group(_group)
                .Channel <TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, _dotNettyOption.TcpNodelay)
                .Option(ChannelOption.WriteBufferHighWaterMark, _dotNettyOption.WriteBufferHighWaterMark)
                .Option(ChannelOption.WriteBufferLowWaterMark, _dotNettyOption.WriteBufferLowWaterMark)
                .Option(ChannelOption.SoReuseaddr, _dotNettyOption.SoReuseaddr)
                .Option(ChannelOption.AutoRead, true)
                .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    pipeline.AddLast(new LoggingHandler(typeof(DotNettyConnection)));
                    pipeline.AddLast("fdfs-write", new ChunkedWriteHandler <IByteBuffer>());
                    pipeline.AddLast("fdfs-decoder", ServiceProvider.CreateInstance <FastDFSDecoder>(new Func <TransportContext>(() => _context)));
                    pipeline.AddLast("fdfs-handler", ServiceProvider.CreateInstance <FastDFSHandler>(new Action <ReceivedPackage>(HandleReceivedPack), new Func <Exception, Task>(HandleExceptionCaught)));
                }));

                _channel = await _bootStrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(ConnectionAddress.IPAddress), ConnectionAddress.Port));

                IsConnected = true;
                Logger.LogInformation($"Client connect! serverEndPoint:{_channel.RemoteAddress.ToStringAddress()},localAddress:{_channel.LocalAddress.ToStringAddress()}");
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
                IsConnected = false;
                await _group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Performs the opening handshake
        /// When call this method you <c>MUST NOT</c> retain the <see cref="IHttpRequest"/> which is passed in.
        /// </summary>
        /// <param name="channel">Channel</param>
        /// <param name="req">HTTP Request</param>
        /// <param name="responseHeaders">Extra headers to add to the handshake response or <code>null</code> if no extra headers should be added</param>
        /// <returns></returns>
        public Task HandshakeAsync(IChannel channel, IHttpRequest req, HttpHeaders responseHeaders)
        {
            if (req is IFullHttpRequest request)
            {
                return(HandshakeAsync(channel, request, responseHeaders));
            }
#if DEBUG
            if (Logger.DebugEnabled)
            {
                Logger.WebSocketVersionServerHandshake(channel, _version);
            }
#endif
            IChannelPipeline       p   = channel.Pipeline;
            IChannelHandlerContext ctx = p.Context <HttpRequestDecoder>();
            if (ctx is null)
            {
                // this means the user use an HttpServerCodec
                ctx = p.Context <HttpServerCodec>();
                if (ctx is null)
                {
                    return(ThrowHelper.ThrowInvalidOperationException_NoHttpDecoderAndServerCodec());
                }
            }

            // Add aggregator and ensure we feed the HttpRequest so it is aggregated. A limit o 8192 should be more then
            // enough for the websockets handshake payload.
            //
            // TODO: Make handshake work without HttpObjectAggregator at all.
            string aggregatorName = "httpAggregator";
            _ = p.AddAfter(ctx.Name, aggregatorName, new HttpObjectAggregator(8192));
            var completion = channel.NewPromise();
            _ = p.AddAfter(aggregatorName, "handshaker", new Handshaker(this, channel, responseHeaders, completion));
            try
            {
                _ = ctx.FireChannelRead(ReferenceCountUtil.Retain(req));
            }
            catch (Exception cause)
            {
                _ = completion.TrySetException(cause);
            }
            return(completion.Task);
        }
Exemplo n.º 20
0
        public async Task Run()
        {
            MultithreadEventLoopGroup bossGroup   = new MultithreadEventLoopGroup();
            MultithreadEventLoopGroup workerGroup = new MultithreadEventLoopGroup();

            try
            {
                ServerBootstrap b = new ServerBootstrap();
                b.Group(bossGroup, workerGroup)
                .Channel <TcpServerSocketChannel>()
                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    pipeline.AddLast("decoder", new StringDecoder());
                    pipeline.AddLast("encoder", new StringEncoder());
                    pipeline.AddLast("handler", new StringHandler());

                    Log.Info("initChannel:" + channel.RemoteAddress);
                }))
                .Option(ChannelOption.SoBacklog, 128)
                .ChildOption(ChannelOption.SoKeepalive, true);

                Log.Info("tcp server start......");

                IChannel f = await b.BindAsync(port);

                await f.CloseCompletion;
            }
            catch (Exception ex)
            {
                Log.Error("tcp server start error.");
            }
            finally
            {
                await workerGroup.ShutdownGracefullyAsync();

                await bossGroup.ShutdownGracefullyAsync();

                Log.Info("tcp server close");
            }
        }
Exemplo n.º 21
0
        public async Task RunEngineAsync(int port, IBasicHandler basicHandler, ICustomizeHandler handler)
        {
            bossGroup   = new MultithreadEventLoopGroup(1);
            workerGroup = new MultithreadEventLoopGroup();
            MessageDispatcher                 dispatcher   = new MessageDispatcher(this.BasicController, basicHandler, handler);
            List <ChannelServerHandler>       handlers     = new List <ChannelServerHandler>();
            RingObject <ChannelServerHandler> ringHandlers = null;

            if (!useDefaultThread)//此处相比默认handler增加了工作线程,默认工作线程为cpu核心*2
            {
                for (int i = 0; i < workThreadCount; i++)
                {
                    WorkerEngine <RequestInfo> workerEngine = new WorkerEngine <RequestInfo>(3000, 1, dispatcher.Process);
                    workerEngine.Start();
                    handlers.Add(new ChannelServerHandler(this.userManager, workerEngine));
                }
                ringHandlers = new RingObject <ChannelServerHandler>(handlers);
            }
            else
            {
                var cChannelHandlers = new List <ChannelServerHandler>()
                {
                    new ChannelServerHandler(this.userManager, dispatcher)
                };
                ringHandlers = new RingObject <ChannelServerHandler>(cChannelHandlers);
            }
            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(OFrameDecoder.NewOFrameDecoder());
                pipeline.AddLast(ringHandlers.GetNext());
            }));

            IChannel bootstrapChannel = await bootstrap.BindAsync(port);
        }
Exemplo n.º 22
0
        public async Task <IChannel> startHttpPortAsync(string lport)
        {
            //X509Certificate2 tlsCertificate = null;
            //if (ServerSettings.IsSsl)
            //{
            //    tlsCertificate = new X509Certificate2(Path.Combine(commSetting.ProcessDirectory, "dotnetty.com.pfx"), "password");
            //}
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;
            }
            try
            {
                httpbootstrap.Group(httpbossGroup, httpworkerGroup);
                httpbootstrap.Channel <CustHttpServerSocketChannel>();

                httpbootstrap
                .Option(ChannelOption.SoBacklog, 8192)

                .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
                {
                    IChannelPipeline pipeline = channel.Pipeline;

                    //  pipeline.AddLast("encoder", new HttpResponseEncoder());
                    pipeline.AddLast("decoder", new HttpRequestDecoder(maxInitialLineLength, maxHeaderSize, maxChunkSize, true));
                    pipeline.AddLast("decoder2", new HttpObjectAggregator(maxContentLength));
                    pipeline.AddLast("handler", new HttpProxyServerHandler());
                }))
                .ChildOption(ChannelOption.SoKeepalive, true);

                httpbootstrapChannel = await httpbootstrap.BindAsync(IPAddress.IPv6Any, int.Parse(lport));

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

                return(httpbootstrapChannel);
            }
            catch (Exception ex)
            {
                Task.WaitAll(httpbossGroup.ShutdownGracefullyAsync(), httpworkerGroup.ShutdownGracefullyAsync());
                throw new Exception("服务启动失败");
            }
        }
Exemplo n.º 23
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            workerGroup = new MultithreadEventLoopGroup(configuration.EventLoopCount);
            var bootstrap = new Bootstrap();

            bootstrap.Group(workerGroup)
            .Channel <SocketDatagramChannel>()
            .Option(ChannelOption.SoBroadcast, true)
            .Handler(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                pipeline.AddLast(new UdpHandler(Provider.GetRequiredService <ILogger <UdpHandler> >()));
                var lengthFieldLength = configuration.LengthFieldLength;
                pipeline.AddLast(new LengthFieldBasedFrameDecoder(ByteOrder.BigEndian,
                                                                  configuration.MaxFrameLength, 0, lengthFieldLength, 0, lengthFieldLength, true));
                pipeline.AddLast(new RequestDecoder(decoder), new UdpLengthFieldPrepender(lengthFieldLength), new ResponseEncoder(encoder), handler);
            }));
            logger.LogInformation($"Server start at {IPAddress.Any}:{configuration.Port}.");
            bootstrapChannel = await bootstrap.BindAsync(configuration.Port);
        }
        Task <IChannel> NewServer(bool autoRead, params IChannelHandler[] handlers)
        {
            Assert.True(handlers.Length >= 1);

            var serverBootstrap = new ServerBootstrap();

            serverBootstrap.Group(this.group)
            .Channel <TcpServerSocketChannel>()
            .ChildOption(ChannelOption.AutoRead, autoRead)
            .ChildHandler(
                new ActionChannelInitializer <IChannel>(
                    ch =>
            {
                IChannelPipeline pipeline = ch.Pipeline;
                pipeline.AddLast(new OneByteToThreeStringsDecoder());
                pipeline.AddLast(handlers);
            }));

            return(serverBootstrap.BindAsync(IPAddress.Loopback, 0));
        }
Exemplo n.º 25
0
        private Bootstrap CreateBootstrap(IEventLoopGroup group)
        {
            ClientHandler handler   = new ClientHandler(_clientInvoker, _config.RpcSerializer);
            Bootstrap     bootstrap = new Bootstrap()
                                      .Group(group)
                                      .Channel <TcpSocketChannel>()
                                      .Option(ChannelOption.SoSndbuf, _config.SoSndbuf)
                                      .Option(ChannelOption.SoRcvbuf, _config.SoRcvbuf)
                                      .Option(ChannelOption.SoReuseaddr, true)
                                      .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                //pipeline.AddLast(new IdleStateHandler(0, 0, _config.AllIdleTimeSeconds));
                pipeline.AddLast("framing-enc", new LengthFieldPrepender(4));
                pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4));
                pipeline.AddLast(handler);
            }));

            return(bootstrap);
        }
Exemplo n.º 26
0
 public TcpClient(IServiceProvider serviceProvider, ITcpClientSessionManager sessionManager, ILogger <TcpClient> logger, IOptions <GatewayConfiguration> configuration)
 {
     this.logger         = logger;
     this.sessionManager = sessionManager;
     this.configuration  = configuration.Value;
     eventLoopGroup      = new MultithreadEventLoopGroup();
     bootstrap           = new Bootstrap().Group(eventLoopGroup)
                           .Channel <TcpSocketChannel>()
                           .Option(ChannelOption.TcpNodelay, true)
                           .Option(ChannelOption.ConnectTimeout, TimeSpan.FromSeconds(30))
                           .Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
     {
         var scope = serviceProvider.CreateScope().ServiceProvider;
         IChannelPipeline pipeline = channel.Pipeline;
         pipeline.AddLast(new IdleStateHandler(this.configuration.BrabchServerReaderIdleTimeSeconds, this.configuration.BrabchServerWriterIdleTimeSeconds, this.configuration.BrabchServerAllIdleTimeSeconds));
         pipeline.AddLast(scope.GetRequiredService <TcpMetadataDecoder>());
         pipeline.AddLast(scope.GetRequiredService <TcpMetadataEncoder>());
         pipeline.AddLast(scope.GetRequiredService <TcpClientHandler>());
     }));
 }
Exemplo n.º 27
0
        public ServerChannel(IContainer container, IChannelPipeline pipeline, IByteBuffer buffer, IFramer framer, ConfigurationSetting setting)
            : base(buffer, framer)
        {
            Ensure.IsNotNull(container);
            Ensure.IsNotNull(pipeline);
            Ensure.IsNotNull(buffer);
            Ensure.IsNotNull(framer);

            SendingBufferSize   = setting.SocketSendBufferSize;
            ReceivingBufferSize = setting.SocketReceiveBufferSize;

            _container = container;
            _setting   = setting;

            this.pipeline = pipeline;

            _channelPipelineFactory?.Invoke(pipeline);

            SetSocket(SocketUtils.CreateSocket());
        }
Exemplo n.º 28
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="clientStub"></param>
 /// <param name="serviceType"></param>
 internal TCPClient(ClientStub clientStub, Type serviceType) : base(clientStub, serviceType)
 {
     _responseWaits = new ResponseWaits(RequestTimeoutSeconds);
     _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(2));
         //数据包最大长度
         pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));
         ClientHandler clientHandler = new ClientHandler(_responseWaits)
         {
             OnDeserializeMessage = DeserializeMessage
         };
         pipeline.AddLast(clientHandler);
     }));
 }
Exemplo n.º 29
0
        /// <summary>
        /// Starts the network.
        /// </summary>
        static async Task Bootstrap()
        {
            var boss      = new MultithreadEventLoopGroup(1);
            var worker    = new MultithreadEventLoopGroup();
            var bootstrap = new ServerBootstrap();

            bootstrap.Group(boss, worker);
            bootstrap.Option(ChannelOption.SoKeepalive, true);
            bootstrap.Channel <TcpServerSocketChannel>();
            bootstrap.ChildHandler(new ActionChannelInitializer <ISocketChannel>((ch) =>
            {
                IChannelPipeline pipeline = ch.Pipeline;

                pipeline.AddLast("decoder", new ConnectionDecoder());
                pipeline.AddLast("encoder", new ConnectionEncoder());
                pipeline.AddLast("handler", new NetworkHandler(ch));
            }));

            await bootstrap.BindAsync(IPAddress.Any, Constants.HOST_PORT);
        }
Exemplo n.º 30
0
        public async Task Run()
        {
            var bossGroup   = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup(5);
            var bootstrap   = new ServerBootstrap();

            bootstrap
            .Group(bossGroup, workerGroup)
            .Channel <TcpServerSocketChannel>()
            .Option(ChannelOption.SoBacklog, 100)
            .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                pipeline.AddLast(new DeCoder());
                pipeline.AddLast(new EnCoder());
                pipeline.AddLast(new EnCoder2());
                pipeline.AddLast(new EchoServerHandler());
            }));
            bootstrapChannel = await bootstrap.BindAsync(2012);
        }
Exemplo n.º 31
0
        private void Init()
        {
            receiveGroup = new MultithreadEventLoopGroup();
            workGroup    = new MultithreadEventLoopGroup();

            bootstrap = new ServerBootstrap();
            bootstrap.Group(receiveGroup, workGroup);
            bootstrap.Channel <TcpServerSocketChannel>();
            bootstrap.ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                pipeline.AddLast(new ProtobufVarint32FrameDecoder());
                pipeline.AddLast(new ProtobufDecoder(ImMessageContext.Parser));
                pipeline.AddLast(new ProtobufVarint32LengthFieldPrepender());
                pipeline.AddLast(new ProtobufEncoder());
                pipeline.AddLast(new IdleStateHandler(IMConstants.READERIDLE_TIMEOUT_SECONDS, IMConstants.WRITERIDLE_TIMEOUT_SECONDS, 0));

                pipeline.AddLast(new ServerChannelHandler(this.ServerEngineOption, this.Receivers));
            }));
        }
 void HandleReadException(IChannelPipeline pipeline, IByteBuffer byteBuf, Exception cause, bool close)
 {
     if (byteBuf != null)
     {
         if (byteBuf.IsReadable())
         {
             this.Channel.ReadPending = false;
             pipeline.FireChannelRead(byteBuf);
         }
         else
         {
             byteBuf.Release();
         }
     }
     pipeline.FireChannelReadComplete();
     pipeline.FireExceptionCaught(cause);
     if (close || cause is SocketException)
     {
         this.CloseOnRead();
     }
 }