private static void AssertWrite(IChannelHandler handler, int count)
        {
            IByteBuffer     buffer  = Unpooled.CopiedBuffer("Test", Encoding.ASCII);
            EmbeddedChannel channel = new EmbeddedChannel(handler);

            channel.Configuration.WriteBufferLowWaterMark  = 1;
            channel.Configuration.WriteBufferHighWaterMark = 3;

            IByteBuffer[] buffers = new IByteBuffer[count];
            for (int i = 0; i < buffers.Length; i++)
            {
                buffers[i] = buffer.RetainedDuplicate();
            }
            Assert.True(channel.WriteOutbound(buffers));
            Assert.True(channel.Finish());
            try
            {
                channel.CloseCompletion.GetAwaiter().GetResult();
            }
            catch { }

            for (int i = 0; i < buffers.Length; i++)
            {
                AssertBuffer(channel, buffer);
            }
            buffer.Release();
            Assert.Null(channel.ReadOutbound());
        }
Exemple #2
0
 protected AbstractEndpoint(URL url, IChannelHandler handler) : base(url, handler)
 {
     Logger              = ObjectFactory.GetInstance <ILogger>();
     this.Codec          = GetChannelCodec(url);
     this.Timeout        = url.GetPositiveParameter(Constants.TimeoutKey, Constants.DefaultTimeout);
     this.ConnectTimeout = url.GetPositiveParameter(Constants.ConnectTimeoutKey, Constants.DefaultConnectTimeout);
 }
Exemple #3
0
        void Setup(bool register, params IChannelHandler[] handlers)
        {
            if (handlers is null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.handlers);
            }

            IChannelPipeline p = Pipeline;

            p.AddLast(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                for (int i = 0; i < handlers.Length; i++)
                {
                    IChannelHandler h = handlers[i];
                    if (h is null)
                    {
                        break;
                    }
                    pipeline.AddLast(h);
                }
            }));

            if (register)
            {
                Task future = _loop.RegisterAsync(this);
                Debug.Assert(future.IsCompleted);
            }
        }
        public IChannelPipeline AddLast(IEventExecutorGroup group, string name, IChannelHandler handler)
        {
            Contract.Requires(handler != null);

            AbstractChannelHandlerContext newCtx;

            lock (this)
            {
                CheckMultiplicity(handler);

                newCtx = this.NewContext(group, this.FilterName(name, handler), handler);
                IEventExecutor executor = this.ExecutorSafe(newCtx.executor);

                this.AddLast0(newCtx);

                // If the executor is null it means that the channel was not registered on an eventloop yet.
                // In this case we add the context to the pipeline and add a task that will call
                // ChannelHandler.handlerAdded(...) once the channel is registered.
                if (executor == null)
                {
                    this.CallHandlerCallbackLater(newCtx, true);
                    return(this);
                }

                if (!executor.InEventLoop)
                {
                    executor.Execute(CallHandlerAddedAction, this, newCtx);
                    return(this);
                }
            }
            this.CallHandlerAdded0(newCtx);
            return(this);
        }
Exemple #5
0
        protected override void Init(IChannel channel)
        {
            SetChannelOptions(channel, this.Options, Logger);

            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));
            }));
        }
Exemple #6
0
 protected static IChannelHandler WrapChannelHandler(URL url, IChannelHandler handler)
 {
     //url = ExecutorUtil.setThreadName(url, ClientThreadPoolName);
     url = url.AddParameterIfAbsent(Constants.ThreadpoolKey, Constants.DefaultClientThreadpool);
     return(new MultiMessageHandler(
                new HeartbeatHandler(ObjectFactory.GetInstance <IDispatcher>().Dispatch(handler, url))));
 }
Exemple #7
0
 public AbstractConnectionFactory(Codec codec, IChannelHandler heartbeatHandler, IChannelHandler handler, ConfigurableInstance confInstance)
 {
     this.confInstance     = confInstance;
     this.codec            = codec ?? throw new ArgumentException("null codec");
     this.heartbeatHandler = heartbeatHandler;
     this.handler          = handler ?? throw new ArgumentException("null handler");
 }
Exemple #8
0
        private void Item_Completed(object sender, SocketAsyncEventArgs e)
        {
            acceptEvent.Set();
            IChannelHandler handler = null;
            SocketArgEvent  arg     = new SocketArgEvent();
            IPEndPoint      point   = e.AcceptSocket.RemoteEndPoint as IPEndPoint;

            arg.remoteIP   = point.Address.ToString();
            arg.remotePort = point.Port;
            point          = e.AcceptSocket.LocalEndPoint as IPEndPoint;
            arg.localIP    = point.Address.ToString();
            arg.localPort  = point.Port;
            arg.chanel     = socketChannel;
            TCPSocketChannel channel = new TCPSocketChannel();

            channel.HandlerTypes   = this.handers;
            channel.Socket         = e.AcceptSocket;
            channel.SocketArgEvent = arg;
            arg.chanel             = channel;
            if (handers.TryGetValue(HanderType.ReadWrite, out handler))
            {
                handler.ChannelActive(arg);
            }
            lock (lock_obj)
            {
                channels.Add(arg);
            }
            Interlocked.Increment(ref m_numConnectedSockets);
            FreeArgEvent(e);
            WorkThread();
        }
 public DefaultChannelHandlerContext(DefaultChannelPipeline pipeline, IChannelHandlerInvoker invoker, string name,
     IChannelHandler handler)
     : base(pipeline, invoker, name, GetSkipPropagationFlags(handler))
 {
     Contract.Requires(handler != null);
     Handler = handler;
 }
        IChannelHandler Replace(
            AbstractChannelHandlerContext ctx, IChannelHandler newHandler)
        {
            Contract.Requires(ctx != this.head && ctx != this.tail);

            lock (this.head)
            {
                var newCtx = new DefaultChannelHandlerContext(this, null, null, newHandler);

                CheckMultiplicity(newCtx);

                AbstractChannelHandlerContext prev = ctx.Prev;
                AbstractChannelHandlerContext next = ctx.Next;
                newCtx.Prev = prev;
                newCtx.Next = next;

                // Finish the replacement of oldCtx with newCtx in the linked list.
                // Note that this doesn't mean events will be sent to the new handler immediately
                // because we are currently at the event handler thread and no more than one handler methods can be invoked
                // at the same time (we ensured that in replace().)
                prev.Next = newCtx;
                next.Prev = newCtx;

                // update the reference to the replacement so forward of buffered content will work correctly
                ctx.Prev = newCtx;
                ctx.Next = newCtx;

                // Invoke newHandler.handlerAdded() first (i.e. before oldHandler.handlerRemoved() is invoked)
                // because callHandlerRemoved() will trigger inboundBufferUpdated() or flush() on newHandler and those
                // event handlers must be called after handlerAdded().
                this.CallHandlerAdded(newCtx);
                this.CallHandlerRemoved(ctx);
                return(ctx.Handler);
            }
        }
Exemple #11
0
 private ServerBootstrap(ServerBootstrap bootstrap)
     : base(bootstrap)
 {
     _childGroup   = bootstrap._childGroup;
     _childHandler = bootstrap._childHandler;
     _childOptions = new ConcurrentDictionary <ChannelOption, object>(bootstrap._childOptions);
 }
Exemple #12
0
 public RpcClient(IPEndPoint endPoint)
 {
     EndPoint          = endPoint;
     Interceptor       = new RpcInterceptor(this);
     _resolver         = new RpcClientResolver(this);
     _callbackResolver = new RpcCallbackResolver(this);
 }
Exemple #13
0
        public bool Initialize()
        {
            Log?.Verbose(className, "Initialize", "Initializing Cxp Server Channel");

            channelHandler = CreateChannelHandler();
            if (channelHandler == null)
            {
                Log?.Information(className, "Initialize", "Failed to Initialize Cxp Server Channel");
                return(false);
            }


            bootstrap = new Bootstrap();
            group     = new MultithreadEventLoopGroup();
            encoder   = new StringEncoder();
            decoder   = new StringDecoder();

            bootstrap
            .Group(group)
            .Channel <TcpSocketChannel>()
            .Option(ChannelOption.TcpNodelay, true)
            .Handler(channelHandler);

            Log?.Information(className, "Initialize", "Cxp Server Channel Initialized");
            return(true);
        }
Exemple #14
0
        private void Item_Completed(object sender, SocketAsyncEventArgs e)
        {
            IChannelHandler rwhandler = null;
            IChannelHandler handler   = null;

            if (!handers.TryGetValue(HanderType.Decoder, out handler))
            {
                //如果没有解析类,就直接获取读取管道
                handers.TryGetValue(HanderType.ReadWrite, out rwhandler);
            }
            if (socketArg == null)
            {
                socketArg        = new SocketArgEvent();
                socketArg.chanel = socketChannel;
            }
            socketArg.data       = e.Buffer;
            socketArg.localIP    = localIP;
            socketArg.localPort  = localPort;
            socketArg.remoteIP   = remoteIP;
            socketArg.remotePort = remotePort;
            if (handler != null)
            {
                handler.ChannelRead(socketArg, e.Buffer);
                handler.ChannelReadComplete(socketArg);
            }
            else if (rwhandler != null)
            {
                rwhandler.ChannelRead(socketArg, e.Buffer);
                rwhandler.ChannelReadComplete(socketArg);
            }
        }
 private static EmbeddedChannel CreateClientChannel(IChannelHandler handler)
 {
     return(CreateClientChannel(handler, WebSocketClientProtocolConfig.NewBuilder()
                                .WebSocketUri("ws://localhost:1234/test")
                                .Subprotocol("test-proto-2")
                                .Build()));
 }
 public DefaultChannelHandlerContext(DefaultChannelPipeline pipeline, IChannelHandlerInvoker invoker, string name,
                                     IChannelHandler handler)
     : base(pipeline, invoker, name, GetSkipPropagationFlags(handler))
 {
     Contract.Requires(handler != null);
     Handler = handler;
 }
        internal string GenerateName(IChannelHandler handler)
        {
            ConditionalWeakTable <Type, string> cache = NameCaches[Thread.CurrentThread.ManagedThreadId % NameCaches.Length];
            Type   handlerType = handler.GetType();
            string name        = cache.GetValue(handlerType, GenerateName0);

            lock (this.head)
            {
                // It's not very likely for a user to put more than one handler of the same type, but make sure to avoid
                // any name conflicts.  Note that we don't cache the names generated here.
                if (this.nameContextMap.ContainsKey(name))
                {
                    string baseName = name.Substring(0, name.Length - 1); // Strip the trailing '0'.
                    for (int i = 1;; i++)
                    {
                        string newName = baseName + i;
                        if (!this.nameContextMap.ContainsKey(newName))
                        {
                            name = newName;
                            break;
                        }
                    }
                }
            }

            return(name);
        }
        public IChannelPipeline AddAfter(string baseName, string name, IChannelHandler handler)
        {
            var current = GetContextByName(baseName);

            if (current == null)
            {
                throw new Exception($"Name={baseName}的handler不存在");
            }

            var newNode = new ChannelHandlerContext(this, name, handler);

            var next = current.Next;

            newNode.Prev = current;
            newNode.Next = next;

            current.Next = newNode;
            if (next != null)
            {
                next.Prev = newNode;
            }

            CallHandlerAdded0(newNode);
            return(this);
        }
Exemple #19
0
 EmbeddedChannel CreateChannel(IChannelHandler handler) =>
 new EmbeddedChannel(
     new WebSocketServerProtocolHandler("/test", null, false),
     new HttpRequestDecoder(),
     new HttpResponseEncoder(),
     new MockOutboundHandler(this),
     handler);
Exemple #20
0
        // todo: attrs
        ///// <summary>
        // /// Set the specific {@link AttributeKey} with the given value on every child {@link Channel}. If the value is
        // /// {@code null} the {@link AttributeKey} is removed
        // /// </summary>
        //public <T> ServerBootstrap childAttr(AttributeKey<T> childKey, T value) {
        //    if (childKey == null) {
        //        throw new NullPointerException("childKey");
        //    }
        //    if (value == null) {
        //        childAttrs.remove(childKey);
        //    } else {
        //        childAttrs.put(childKey, value);
        //    }
        //    return this;
        //}
        /// <summary>
        /// Set the {@link ChannelHandler} which is used to serve the request for the {@link Channel}'s.
        /// </summary>
        public ServerBootstrap ChildHandler(IChannelHandler childHandler)
        {
            Contract.Requires(childHandler != null);

            this.childHandler = childHandler;
            return(this);
        }
        IChannelHandler Replace(AbstractChannelHandlerContext ctx, string newName, IChannelHandler newHandler)
        {
            Contract.Requires(newHandler != null);
            Contract.Assert(ctx != this.head && ctx != this.tail);

            AbstractChannelHandlerContext newCtx;

            lock (this)
            {
                CheckMultiplicity(newHandler);
                if (newName == null)
                {
                    newName = this.GenerateName(newHandler);
                }
                else
                {
                    bool sameName = ctx.Name.Equals(newName, StringComparison.Ordinal);
                    if (!sameName)
                    {
                        this.CheckDuplicateName(newName);
                    }
                }

                newCtx = this.NewContext(ctx.executor, newName, newHandler);
                IEventExecutor executor = this.ExecutorSafe(ctx.executor);

                Replace0(ctx, newCtx);

                // If the executor is null it means that the channel was not registered on an event loop yet.
                // In this case we replace the context in the pipeline
                // and add a task that will signal handler it was added or removed
                // once the channel is registered.
                if (executor == null)
                {
                    this.CallHandlerCallbackLater(newCtx, true);
                    this.CallHandlerCallbackLater(ctx, false);
                    return(ctx.Handler);
                }

                if (!executor.InEventLoop)
                {
                    executor.Execute(() =>
                    {
                        // Indicate new handler was added first (i.e. before old handler removed)
                        // because "removed" will trigger ChannelRead() or Flush() on newHandler and
                        // those event handlers must be called after handler was signaled "added".
                        this.CallHandlerAdded0(newCtx);
                        this.CallHandlerRemoved0(ctx);
                    });
                    return(ctx.Handler);
                }
            }
            // Indicate new handler was added first (i.e. before old handler removed)
            // because "removed" will trigger ChannelRead() or Flush() on newHandler and
            // those event handlers must be called after handler was signaled "added".
            this.CallHandlerAdded0(newCtx);
            this.CallHandlerRemoved0(ctx);
            return(ctx.Handler);
        }
Exemple #22
0
        static async Task <Tuple <EmbeddedChannel, SslStream> > SetupStreamAndChannelAsync(bool isClient, IEventExecutor executor, IWriteStrategy writeStrategy, SslProtocols protocol, List <Task> writeTasks, string targetHost)
        {
            IChannelHandler tlsHandler = isClient ?
                                         (IChannelHandler) new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) =>
            {
                Assert.Equal(targetHost, certificate.Issuer.Replace("CN=", string.Empty));
                return(true);
            }), new ClientTlsSettings(SslProtocols.Tls12, false, new List <X509Certificate>(), targetHost)) :
                                         new SniHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ServerTlsSniSettings(CertificateSelector));
            //var ch = new EmbeddedChannel(new LoggingHandler("BEFORE"), tlsHandler, new LoggingHandler("AFTER"));
            var ch = new EmbeddedChannel(tlsHandler);

            if (!isClient)
            {
                // check if in the beginning snihandler exists in the pipeline, but not tls handler
                Assert.NotNull(ch.Pipeline.Get <SniHandler>());
                Assert.Null(ch.Pipeline.Get <TlsHandler>());
            }

            IByteBuffer readResultBuffer = Unpooled.Buffer(4 * 1024);
            Func <ArraySegment <byte>, Task <int> > readDataFunc = async output =>
            {
                if (writeTasks.Count > 0)
                {
                    await Task.WhenAll(writeTasks).WithTimeout(TestTimeout);

                    writeTasks.Clear();
                }

                if (readResultBuffer.ReadableBytes < output.Count)
                {
                    await ReadOutboundAsync(async() => ch.ReadOutbound <IByteBuffer>(), output.Count - readResultBuffer.ReadableBytes, readResultBuffer, TestTimeout);
                }
                Assert.NotEqual(0, readResultBuffer.ReadableBytes);
                int read = Math.Min(output.Count, readResultBuffer.ReadableBytes);
                readResultBuffer.ReadBytes(output.Array, output.Offset, read);
                return(read);
            };
            var mediationStream = new MediationStream(readDataFunc, input =>
            {
                Task task = executor.SubmitAsync(() => writeStrategy.WriteToChannelAsync(ch, input)).Unwrap();
                writeTasks.Add(task);
                return(task);
            });

            var driverStream = new SslStream(mediationStream, true, (_1, _2, _3, _4) => true);

            if (isClient)
            {
                await Task.Run(() => driverStream.AuthenticateAsServerAsync(CertificateSelector(targetHost).Result.Certificate).WithTimeout(TimeSpan.FromSeconds(5)));
            }
            else
            {
                await Task.Run(() => driverStream.AuthenticateAsClientAsync(targetHost, null, protocol, false)).WithTimeout(TimeSpan.FromSeconds(5));
            }
            writeTasks.Clear();

            return(Tuple.Create(ch, driverStream));
        }
Exemple #23
0
 ServerBootstrap(ServerBootstrap bootstrap)
     : base(bootstrap)
 {
     this.childGroup   = bootstrap.childGroup;
     this.childHandler = bootstrap.childHandler;
     this.childOptions = new ConcurrentDictionary <ChannelOption, ChannelOptionValue>(bootstrap.childOptions);
     this.childAttrs   = new ConcurrentDictionary <IConstant, AttributeValue>(bootstrap.childAttrs);
 }
        /// <summary>
        /// Init constructor.
        /// </summary>
        protected ChannelProcessor(IChannelHandler handler, object state)
        {
            if (handler == null)
                throw new ArgumentNullException("handler");

            Handler = handler;
            State = state;
        }
        protected static SkipFlags GetSkipPropagationFlags(IChannelHandler handler)
        {
            Tuple <SkipFlags> skipDirection = SkipTable.GetValue(
                handler.GetType(),
                handlerType => Tuple.Create(CalculateSkipPropagationFlags(handlerType)));

            return(skipDirection?.Item1 ?? 0);
        }
 private static EmbeddedChannel CreateClientChannel(IChannelHandler handler, WebSocketClientProtocolConfig config)
 {
     return(new EmbeddedChannel(
                new HttpClientCodec(),
                new HttpObjectAggregator(8192),
                new WebSocketClientProtocolHandler(config),
                handler));
 }
        public DefaultChannelHandlerContext(
            DefaultChannelPipeline pipeline, IEventExecutor executor, string name, IChannelHandler handler)
            : base(pipeline, executor, name, GetSkipPropagationFlags(handler))
        {
            Contract.Requires(handler != null);

            this.Handler = handler;
        }
        public DefaultChannelHandlerContext(
            DefaultChannelPipeline pipeline, IEventExecutor executor, string name, IChannelHandler handler)
            : base(pipeline, executor, name, GetSkipPropagationFlags(handler))
        {
            Contract.Requires(handler != null);

            this.Handler = handler;
        }
        private void Replace(string targetName, string name, IChannelHandler handler)
        {
            ChannelHandlerContext ctx = CreateContext(name, handler);

            ChannelHandlerContext ctxToReplace = FindContextByName(targetName);

            ctx.LinkReplace(ctxToReplace);
        }
        private void AddBefore(string targetName, string name, IChannelHandler handler)
        {
            ChannelHandlerContext ctx = CreateContext(name, handler);

            ChannelHandlerContext targetCtx = FindContextByName(targetName);

            ctx.LinkBefore(targetCtx);
        }
Exemple #31
0
 protected internal AbstractBootstrap(AbstractBootstrap <TBootstrap, TChannel> clientBootstrap)
 {
     _group          = clientBootstrap._group;
     _channelFactory = clientBootstrap._channelFactory;
     _handler        = clientBootstrap._handler;
     _localAddress   = clientBootstrap._localAddress;
     _options        = new ConcurrentDictionary <ChannelOption, object>(clientBootstrap._options);
 }
Exemple #32
0
        protected static int GetSkipPropagationFlags(IChannelHandler handler)
        {
            var skipDirection = SkipTable.GetValue(
                handler.GetType(),
                handlerType => Tuple.Create(CalculateSkipPropagationFlags(handlerType)));

            return(skipDirection == null ? 0 : skipDirection.Item1);
        }
Exemple #33
0
 public ServerBootstrapAcceptor(
     IEventLoopGroup childGroup, IChannelHandler childHandler,
     Func <IChannelConfiguration, bool> childOptionsSetupFunc)
 {
     this.childGroup            = childGroup;
     this.childHandler          = childHandler;
     this.childOptionsSetupFunc = childOptionsSetupFunc;
 }
        protected static int GetSkipPropagationFlags(IChannelHandler handler)
        {
            Tuple<int> skipDirection = SkipTable.GetValue(
                handler.GetType(),
                handlerType => Tuple.Create(CalculateSkipPropagationFlags(handlerType)));

            return skipDirection == null ? 0 : skipDirection.Item1;
        }
        public void SetUp(BenchmarkContext context)
        {
            _inboundThroughputCounter = context.GetCounter(InboundThroughputCounterName);
            _counterHandlerInbound = new CounterHandlerInbound(_inboundThroughputCounter);
            _outboundThroughputCounter = context.GetCounter(OutboundThroughputCounterName);
            _counterHandlerOutbound = new CounterHandlerOutbound(_outboundThroughputCounter);

            channel = new EmbeddedChannel(_counterHandlerOutbound, _counterHandlerInbound);
        }
 private static void ApplyChannelPipeline(IChannel channel, IChannelHandler handler)
 {
     var encoders = new IChannelHandler[]
     {new LengthFieldPrepender(4, false), new LengthFieldBasedFrameDecoder(10000, 0, 4, 0, 4)};
     var protobuf = new IChannelHandler[] { new ProtobufEncoder(), new ProtobufDecoder(TCP.Wrapper.DefaultInstance) };
     var msg = new IChannelHandler[] { new MsgEncoder(), new MsgDecoder() };
     var pipeline = encoders.Concat(protobuf).Concat(msg).Concat(new IChannelHandler[] { handler });
     foreach (var h in pipeline)
         channel.Pipeline.AddLast(h);
 }
Exemple #37
0
        /// <summary>
        /// Inserts a handler at the first position of this pipeline.
        /// </summary>
        /// <returns></returns>
        public Pipeline AddFirst(string name, IChannelHandler handler)
        {
            CheckDuplicateName(name);
            var item = new HandlerItem(name, handler);
            _name2Item.Add(name, item);

            _handlers.AddFirst(item);
            //handler.HandlerAdded(_ctx);
            return this;
        }
Exemple #38
0
 public static ChannelPipe CreateChannelPipe(IPacketEncoder encoder, IPacketDecoder decoder, IChannelHandler handler)
 {
     var pipe = new ChannelPipe();
     pipe.SetCreateChannelAction((channel) =>
     {
         channel.SetConfig("encoder", encoder);
         channel.SetConfig("decoder", decoder);
         channel.SetConfig("handler", handler);
     });
     return pipe;
 }
        /// <summary>
        /// Init constructor.
        /// </summary>
        protected ChannelProcessor(string channel, string[] segments, IChannelHandler handler, object state)
        {
            if (handler == null)
                throw new ArgumentNullException("handler");
            if (!IsValid(channel))
                throw new ArgumentException("Channel seems to be invalid due to standard validation checks", "channel");

            Channel = channel;
            Segments = segments;
            Handler = handler;
            State = state;
        }
        /// <summary>
        /// Registers new handler to notify, when processing expected channel.
        /// </summary>
        public void Register(string channel, IChannelHandler handler, object state)
        {
            if (string.IsNullOrEmpty(channel))
            {
                RegisterDefault(handler);
            }

            if (handler == null)
                throw new ArgumentNullException("handler");

            _processors.Add(CreateNewProcessor(channel, handler, state));
        }
Exemple #41
0
        private HandShake(IChannel channel, IStep step, IProtocol encryptor)
        {
            if(!(channel is IKeepProtocolChannel))
                throw new InvalidCastException("HandShake에 사용하는 Channel은 IKeepProtocolChannel을 상속하는 클래스여야 합니다.");
            if (!(channel is IKeepHandlerChannel))
                throw new InvalidCastException("HandShake에 사용하는 Channel은 IKeepHandlerChannel을 상속하는 클래스여야 합니다.");

            _channel = channel;
            _step = step;
            _encryptor = encryptor;
            _protocol = ((IKeepProtocolChannel) channel).GetProtocol();
            _handler = ((IKeepHandlerChannel) channel).GetHandler();

            ((IKeepProtocolChannel) channel).SetProtocol(this);
            ((IKeepHandlerChannel) channel).SetHandler(this);
        }
Exemple #42
0
        public static IRpcServer Bind(Uri uri, IChannelHandler[] handlers)
        {
            Contract.Requires(handlers != null && handlers.Any());

            IChannelHandler handler;
            if (handlers.Count() == 1)
            {
                handler = handlers[0];
            }
            else
            {
                handler = new ChannelHandlerDispatcher(handlers);
            }

            var transporter = GetTransporter();
            return transporter.Bind(uri, handler);
        }
Exemple #43
0
        private static IRpcClient Connect(Uri uri, IChannelHandler[] handlers)
        {
            IChannelHandler handler;
            if (!handlers.Any())
            {
                handler = new ChannelHandlerAdapter();
            }
            else if (handlers.Count() == 1)
            {
                handler = handlers[0];
            }
            else
            {
                handler = new ChannelHandlerDispatcher(handlers);
            }

            var transporter = GetTransporter();
            return transporter.Connect(uri, handler);
        }
Exemple #44
0
        private ITcpClientChannel SendTcpPeerConnection(PeerConnection peerConnection, IChannelHandler handler, ChannelCreator channelCreator,
            TaskCompletionSource<Message.Message> tcsResponse)
        {
            // if the channel gets closed, the future should get notified
            var channel = peerConnection.Channel;

            // channel creator can be null if we don't need to create any channels
            if (channelCreator != null)
            {
                // TODO this doesn't do anything yet
                channelCreator.SetupCloseListener(channel, tcsResponse);
            }

            // we need to replace the handler if this comes from the peer that created a peer connection,
            // otherwise we need to add a handler
            AddOrReplace(channel.Pipeline, "dispatcher", "handler", handler);
            // TODO uncommented Java stuff needed?
            return channel as ITcpClientChannel; // TODO this will fail if its a server channel!!!
        }
 /// <summary>
 /// Get context for a specific channel
 /// </summary>
 /// <param name="value"></param>
 public IChannelHandlerContext Get(IChannelHandler value)
 {
     return _contexts[value];
 }
Exemple #46
0
        private ITcpClientChannel SendTcpCreateChannel(IPEndPoint recipient, ChannelCreator channelCreator,
            PeerConnection peerConnection, IChannelHandler handler, TimeoutFactory timeoutHandler, int connectTimeoutMillis)
        {
            // create pipeline
            var handlers = new Dictionary<string, IChannelHandler>();
            if (timeoutHandler != null)
            {
                handlers.Add("timeout0", timeoutHandler.CreateIdleStateHandlerTomP2P());
                handlers.Add("timeout1", timeoutHandler.CreateTimeHandler());
            }
            handlers.Add("decoder", new TomP2PCumulationTcp(ChannelClientConfiguration.SignatureFactory));
            handlers.Add("encoder", new TomP2POutbound(false, ChannelClientConfiguration.SignatureFactory));
            if (peerConnection != null)
            {
                // we expect responses on this connection
                handlers.Add("dispatcher", _dispatcher);
            }
            if (timeoutHandler != null)
            {
                handlers.Add("handler", handler);
            }
            HeartBeat heartBeat = null;
            if (peerConnection != null)
            {
                heartBeat = new HeartBeat(peerConnection.HeartBeatMillis, PingBuilderFactory);
                handlers.Add("heartbeat", heartBeat);
            }

            var channel = channelCreator.CreateTcp(recipient, connectTimeoutMillis, handlers);

            if (peerConnection != null && channel != null)
            {
                peerConnection.SetChannel(channel);
                heartBeat.SetPeerConnection(peerConnection);
            }
            return channel;
        }
Exemple #47
0
 private void AddOrReplace(Pipeline pipeline, string before, string name, IChannelHandler handler)
 {
     if (pipeline.Names.Contains(name))
     {
         pipeline.Replace(name, name, handler);
     }
     else
     {
         if (before == null)
         {
             pipeline.AddFirst(name, handler);
         }
         else
         {
             pipeline.AddBefore(before, name, handler);
         }
     }
 }
        /// <summary>
        /// Registers the default handler.
        /// If during processing a given channel doesn't fit for any handler, this one will get called.
        /// </summary>
        public void RegisterDefault(IChannelHandler handler, object state)
        {
            if (handler == null)
                throw new ArgumentNullException("handler");

            DefaultProcessor = new BasicChannelProcessor(handler, state);
        }
 public ChannelHandlerDispatcher(IChannelHandler[] handlers)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// Registers new handler to notify, when processing expected channel.
 /// </summary>
 public void Register(string channel, IChannelHandler handler)
 {
     Register(channel, handler, null);
 }
 /// <summary>
 /// Init constructor.
 /// </summary>
 public BasicChannelProcessor(IChannelHandler handler, object state)
     : base(handler, state)
 {
 }
Exemple #52
0
 public static ChannelPipe CreateChannelPipe(IChannelHandler handler)
 {
     return CreateChannelPipe(LinefeedEncoder.Encoder, LinefeedEncoder.Encoder, handler);
 }
 /// <summary>
 /// Registers the default handler.
 /// If during processing a given channel doesn't fit for any handler, this one will get called.
 /// </summary>
 public void RegisterDefault(IChannelHandler handler)
 {
     RegisterDefault(handler, null);
 }
Exemple #54
0
 public IChannelHandler SetHandler(IChannelHandler handler)
 {
     _handler = handler;
     return _handler;
 }
Exemple #55
0
 public virtual IChannelHandler SetHandler(IChannelHandler handler)
 {
     _handler = handler;
     return handler;
 }
 /// <summary>
 /// Init constructor.
 /// </summary>
 public BasicChannelProcessor(string channel, string[] segments, IChannelHandler handler, object state)
     : base(channel, segments, handler, state)
 {
 }
 /// <summary>
 /// Init constructor.
 /// </summary>
 public GlobalWildcardChannelProcessor(string channel, string[] segments, IChannelHandler handler, object state)
     : base(channel, segments, handler, state)
 {
 }
        private ChannelProcessor CreateNewProcessor(string channel, IChannelHandler handler, object state)
        {
            var segments = channel.Split('/');
            int globalWildcardIndex = channel.IndexOf("/**");
            int singleWildcardIndex = channel.IndexOf('*');

            if (globalWildcardIndex >= 0)
            {
                if (globalWildcardIndex != channel.Length - 3)
                    throw new NotSupportedException("Global wildcards are only supported at the end of the channel");
                return new GlobalWildcardChannelProcessor(channel, segments, handler, state);
            }

            if (singleWildcardIndex >= 0)
                return new WildcardChannelProcessor(channel, segments, handler, state);

            return new BasicChannelProcessor(channel, segments, handler, state);
        }
Exemple #59
0
 public HandlerItem(string name, IChannelHandler handler)
     : this()
 {
     Name = name;
     Handler = handler;
 }
        public static Task<IChannel> CreateConnection(Role role, IPEndPoint socketAddress, int poolSize, IChannelHandler upstreamHandler)
        {
            if (role == Role.Client)
            {
                var connection = new ClientBootstrap()
                    .ChannelFactory(() => new TcpSocketChannel(socketAddress.AddressFamily))
                    .Option(ChannelOption.TcpNodelay, true)
                    .Group(GetClientWorkerPool(poolSize))
                    .Handler(new ActionChannelInitializer<TcpSocketChannel>(channel =>
                    {
                        ApplyChannelPipeline(channel, upstreamHandler);
                    }));

                return connection.ConnectAsync(socketAddress);
            }
            else //server
            {
                var connection = new ServerBootstrap()
                    .Group(GetServerPool(poolSize), GetServerWorkerPool(poolSize))
                    .ChannelFactory(() => new TcpServerSocketChannel(socketAddress.AddressFamily))
                    .ChildOption(ChannelOption.TcpNodelay, true)
                    .ChildHandler(new ActionChannelInitializer<TcpSocketChannel>(channel =>
                    {
                        ApplyChannelPipeline(channel, upstreamHandler);
                    }));
                return connection.BindAsync(socketAddress);
            }
        }