Example #1
0
        private void InitializeUdpChannel()
        {
            if (_logger.IsInfo)
            {
                _logger.Info($"Starting Discovery UDP Channel: {_networkConfig.MasterHost}:{_networkConfig.MasterPort}");
            }
            _group = new MultithreadEventLoopGroup(1);
            var bootstrap = new Bootstrap();

            bootstrap
            .Group(_group);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                bootstrap
                .ChannelFactory(() => new SocketDatagramChannel(AddressFamily.InterNetwork))
                .Handler(new ActionChannelInitializer <IDatagramChannel>(InitializeChannel));
            }
            else
            {
                bootstrap
                .Channel <SocketDatagramChannel>()
                .Handler(new ActionChannelInitializer <IDatagramChannel>(InitializeChannel));
            }

            _bindingTask = bootstrap.BindAsync(IPAddress.Parse(_networkConfig.MasterHost), _networkConfig.MasterPort)
                           .ContinueWith(t => _channel = t.Result);
        }
Example #2
0
        public void init(ChannelConfig channelConfig, ExecutorPool executorPool, IEventLoopGroup eventLoopGroup)
        {
            if (channelConfig.UseConvChannel)
            {
                var convIndex = 0;
                if (channelConfig.Crc32Check)
                {
                    convIndex += Ukcp.HEADER_CRC;
                }
                if (channelConfig.FecDataShardCount != 0 && channelConfig.FecParityShardCount != 0)
                {
                    convIndex += Fec.fecHeaderSizePlus2;
                }
                _channelManager = new ClientConvChannelManager(convIndex);
            }
            else
            {
                _channelManager = new ClientEndPointChannelManager();
            }

            //初始化线程池 创建一个线程就够了
            _executorPool = executorPool;
            _executorPool.CreateMessageExecutor();
            _eventLoopGroup = eventLoopGroup;

            bootstrap = new Bootstrap();
            bootstrap.Group(_eventLoopGroup);
            bootstrap.ChannelFactory(() => new SocketDatagramChannel(AddressFamily.InterNetwork));
            bootstrap.Handler(new ActionChannelInitializer <SocketDatagramChannel>(channel =>
            {
                var pipeline = channel.Pipeline;
                pipeline.AddLast(new ClientChannelHandler(_channelManager, channelConfig));
            }));
        }
Example #3
0
        private void InitializeUdpChannel()
        {
            if (_logger.IsDebug)
            {
                _logger.Debug($"Discovery    : udp://{_networkConfig.LocalIp}:{_networkConfig.DiscoveryPort}");
            }
            ThisNodeInfo.AddInfo("Discovery    :", $"udp://{_networkConfig.LocalIp}:{_networkConfig.DiscoveryPort}");
            _group = new MultithreadEventLoopGroup(1);
            Bootstrap bootstrap = new Bootstrap();

            bootstrap
            .Group(_group);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                bootstrap
                .ChannelFactory(() => new SocketDatagramChannel(AddressFamily.InterNetwork))
                .Handler(new ActionChannelInitializer <IDatagramChannel>(InitializeChannel));
            }
            else
            {
                bootstrap
                .Channel <SocketDatagramChannel>()
                .Handler(new ActionChannelInitializer <IDatagramChannel>(InitializeChannel));
            }

            _bindingTask = bootstrap.BindAsync(IPAddress.Parse(_networkConfig.LocalIp), _networkConfig.DiscoveryPort)
                           .ContinueWith(t => _channel = t.Result);
        }
Example #4
0
        public void init(IExecutorPool executorPool, KcpListener kcpListener, ChannelConfig channelConfig, params int[] ports)
        {
            if (channelConfig.UseConvChannel)
            {
                int convIndex = 0;
                if (channelConfig.Crc32Check)
                {
                    convIndex += Ukcp.HEADER_CRC;
                }
                if (channelConfig.FecDataShardCount != 0 && channelConfig.FecParityShardCount != 0)
                {
                    convIndex += Fec.fecHeaderSizePlus2;
                }
                _channelManager = new ServerConvChannelManager(convIndex);
            }
            else
            {
                _channelManager = new ServerEndPointChannelManager();
            }

            int cpuNum    = Environment.ProcessorCount;
            int bindTimes = cpuNum;

            _eventLoopGroup = new MultithreadEventLoopGroup(cpuNum);
            _scheduleThread = new HashedWheelScheduleThread();

            _bootstrap = new Bootstrap();
            //TODO epoll模型 服务器端怎么支持?得试试成功没有
            _bootstrap.Option(ChannelOption.SoReuseport, true);

            _bootstrap.Option(ChannelOption.SoReuseaddr, true);
            _bootstrap.Group(_eventLoopGroup);
            _bootstrap.ChannelFactory(() => new SocketDatagramChannel(AddressFamily.InterNetwork));
            _bootstrap.Handler(new ActionChannelInitializer <SocketDatagramChannel>(channel =>
            {
                var pipeline = channel.Pipeline;
                pipeline.AddLast(new ServerChannelHandler(_channelManager, channelConfig, executorPool, kcpListener, _scheduleThread));
            }));

            foreach (var port in ports)
            {
                //                for (int i = 0; i < bindTimes; i++) {
                var task = Task.Run(() => _bootstrap.BindAsync(port));
                task.Wait();
                var channel = task.Result;
                _localAddress.Add(channel);
//                }
            }

            //TODO 如何启动关闭进程的钩子??
        }
Example #5
0
 private async void Connect()
 {
     await Task.Run(() =>
     {
         var group     = new MultithreadEventLoopGroup(3);
         var bootstrap = new Bootstrap();
         bootstrap.Group(group);
         bootstrap.ChannelFactory(() => new TcpSocketChannel(_endPoint.AddressFamily));
         bootstrap.Option(ChannelOption.TcpNodelay, true);
         bootstrap.Option(ChannelOption.SoLinger, 0);
         bootstrap.Option(ChannelOption.SoRcvbuf, 8192);
         bootstrap.Option(ChannelOption.SoSndbuf, 8192);
         bootstrap.Handler(this);
         bootstrap.ConnectAsync(_endPoint);
     });
 }
Example #6
0
        protected override async Task <IClient> CreateClient(URL url)
        {
            Settings = NettyTransportSettings.Create(url);

            var protocol = _nettyProtocols[url.Protocol];

            IEventLoopGroup group = protocol.EventLoopGroupType
                                    .GetConstructor(Array.Empty <Type>())
                                    .Invoke(Array.Empty <object>()) as IEventLoopGroup;

            IChannel clientChannel = protocol.ChannelType
                                     .GetConstructor(Array.Empty <Type>())
                                     .Invoke(Array.Empty <object>()) as IChannel;

            var isSsl = url.GetParameter(SSL_KEY, DEFAULT_SSL);

            X509Certificate2 cert       = null;
            string           targetHost = null;

            if (isSsl)
            {
                var pfx = url.GetParameter(PFX_KEY, DEFAULT_PFX);
                var pwd = url.GetParameter(PWD_KEY, DEFAULT_PWD);
                cert       = new X509Certificate2(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{pfx}.pfx"), pwd);
                targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
            }


            var bootstrap = new Bootstrap();

            bootstrap
            .ChannelFactory(() => clientChannel)
            .Option(ChannelOption.SoReuseaddr, Settings.TcpReuseAddr)
            .Option(ChannelOption.SoKeepalive, Settings.TcpKeepAlive)
            .Option(ChannelOption.TcpNodelay, Settings.TcpNoDelay)
            .Option(ChannelOption.ConnectTimeout, Settings.ConnectTimeout)
            .Option(ChannelOption.AutoRead, true)
            .Option(ChannelOption.Allocator, PooledByteBufferAllocator.Default)
            .Group(group)
            .Handler(new ActionChannelInitializer <IChannel>(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(new LengthFieldPrepender(4));
                //pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4));

                pipeline.AddLast(new NettyLoggingHandler());
                SetInitialChannelPipeline(channel);
                pipeline.AddLast(new ClientHandler(ReceivedMessage));
            }));

            if (Settings.ReceiveBufferSize.HasValue)
            {
                bootstrap.Option(ChannelOption.SoRcvbuf, Settings.ReceiveBufferSize.Value);
            }
            if (Settings.SendBufferSize.HasValue)
            {
                bootstrap.Option(ChannelOption.SoSndbuf, Settings.SendBufferSize.Value);
            }
            if (Settings.WriteBufferHighWaterMark.HasValue)
            {
                bootstrap.Option(ChannelOption.WriteBufferHighWaterMark, Settings.WriteBufferHighWaterMark.Value);
            }
            if (Settings.WriteBufferLowWaterMark.HasValue)
            {
                bootstrap.Option(ChannelOption.WriteBufferLowWaterMark, Settings.WriteBufferLowWaterMark.Value);
            }


            var client          = bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(url.Host), url.Port)).GetAwaiter().GetResult();
            var messageListener = new MessageListener();

            client.GetAttribute(messageListenerKey).Set(messageListener);

            var timeout = url.GetParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT);

            await Task.CompletedTask;

            return(new NettyClient(group, client, messageListener, timeout, url));
        }