internal HttpRequestChannel(HttpChannelFactory factory,
                                    EndpointAddress to,
                                    Uri via,
                                    MessageEncoder encoder,
                                    HttpTransportBindingElement bindingElement)
            : base(factory)
        {
            if (to == null)
            {
                throw new ArgumentNullException("to");
            }
            this._factory = factory;
            this._to      = to;
            this._via     = via;
            this._encoder = encoder;

            _listeners = new List <ITrafficListener>();

            foreach (IChannelController controller in bindingElement.Controllers)
            {
                if (controller is ITrafficListener)
                {
                    _listeners.Add((ITrafficListener)controller);
                }

                if (controller is IEndpointController)
                {
                    if (_endpointController != null)
                    {
                        throw new ApplicationException("Only one channel controller of type IAddressProvider can be set");
                    }
                    _endpointController = (IEndpointController)controller;
                }
                if (controller is IExecutionController)
                {
                    if (_executionController != null)
                    {
                        throw new ApplicationException("Only one channel controller of type IExecutionController can be set");
                    }
                    _executionController = (IExecutionController)controller;
                }
                if (controller is ICredentialsProvider)
                {
                    _credentialsProvider = controller as ICredentialsProvider;
                }
            }
            this._networkStream = new RequestNetworkStream(to);

            this._bufferManager = BufferManager.CreateBufferManager(bindingElement.MaxBufferPoolSize, (int)bindingElement.MaxReceivedMessageSize);
        }
Exemple #2
0
        public WebSocketTests(ITestOutputHelper output)
        {
            var logger = new TestLogger(output);

            this.factories = new WebSocketFactoryCollection();
            this.factories.Add(new WebSocketFactoryRfc6455());
            this.options = new WebSocketListenerOptions
            {
                Logger         = logger,
                PingTimeout    = Timeout.InfiniteTimeSpan,
                BufferManager  = BufferManager.CreateBufferManager(10, 1024),
                SendBufferSize = 512
            };
        }
Exemple #3
0
        public void TestDispose()
        {
            const int maxBufferPoolSize = 2 << 32;
            const int maxBufferSize     = 2 << 16;
            var       bufferManager     = BufferManager.CreateBufferManager(maxBufferPoolSize, maxBufferSize);

            var len = 13;
            var buf = bufferManager.TakeBuffer(len);

            var managedBuffer = new ManagedBuffer(buf, len, bufferManager);

            managedBuffer.Dispose();
            managedBuffer.Dispose();
        }
        public XmlBuffer(int maxBufferSize)
        {
            if (maxBufferSize < 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(maxBufferSize), maxBufferSize,
                                                                                                          SR.ValueMustBeNonNegative));
            }

            int initialBufferSize = Math.Min(512, maxBufferSize);

            _stream = new BufferManagerOutputStream(SR.XmlBufferQuotaExceeded, initialBufferSize, maxBufferSize,
                                                    BufferManager.CreateBufferManager(0, int.MaxValue));
            _sections = new List <Section>(1);
        }
Exemple #5
0
        /// <summary>
        /// Initializes a new instance.
        /// </summary>
        /// <param name="router"></param>
        /// <param name="transportElement"></param>
        /// <param name="context"></param>
        public AspNetCoreReplyChannelListener(
            AspNetCoreRequestRouter router,
            AspNetCoreTransportBindingElement transportElement,
            BindingContext context) :
            base(context.Binding)
        {
            this.router = router ?? throw new ArgumentNullException(nameof(router));

            bufferManager  = BufferManager.CreateBufferManager(transportElement.MaxBufferPoolSize, (int)transportElement.MaxReceivedMessageSize);
            encoderFactory = context.BindingParameters.Remove <MessageEncodingBindingElement>().CreateMessageEncoderFactory();
            uri            = new Uri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);
            secure         = transportElement.Secure;
            method         = transportElement.Method;
        }
Exemple #6
0
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();

            string[] splitArgs = null;
            if (args.Length != 1 || (splitArgs = args[0].Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries)).Length != 2)
            {
                Console.WriteLine("usage: EchoClient <hostname>:<port>");
                Console.WriteLine("example:");
                Console.WriteLine("    > EchoClient 127.0.0.1:9211");
                Environment.Exit(-1);
            }

            var endpoint = new IPEndPoint(IPAddress.Parse(splitArgs[0]), int.Parse(splitArgs[1]));

            var cts           = new CancellationTokenSource();
            var bufferManager = BufferManager.CreateBufferManager(2 << 16, 2 << 8);

            var selector = new Selector();

            Task.Factory.StartNew(() => selector.Start(60000000, cts.Token), cts.Token);

            var frameClientSubject = endpoint.ToFrameClientSubject(SocketFlags.None, bufferManager, selector, cts.Token);

            var observerDisposable =
                frameClientSubject
                .SubscribeOn(TaskPoolScheduler.Default)
                .Subscribe(
                    disposableBuffer =>
            {
                Console.WriteLine("Read: " + Encoding.UTF8.GetString(disposableBuffer.Bytes, 0, disposableBuffer.Length));
                disposableBuffer.Dispose();
            },
                    error => Console.WriteLine("Error: " + error.Message),
                    () => Console.WriteLine("OnCompleted: FrameReceiver"));

            Console.In.ToLineObservable()
            .Subscribe(
                line =>
            {
                var writeBuffer = Encoding.UTF8.GetBytes(line);
                frameClientSubject.OnNext(new DisposableBuffer(writeBuffer, writeBuffer.Length, Disposable.Empty));
            },
                error => Console.WriteLine("Error: " + error.Message),
                () => Console.WriteLine("OnCompleted: LineReader"));

            observerDisposable.Dispose();

            cts.Cancel();
        }
Exemple #7
0
        public DvcChannelFactory(DvcBindingElement bindingElement, BindingContext context)
            : base(context.Binding)
        {
            // populate members from binding element
            this.maxBufferSize = (int)bindingElement.MaxReceivedMessageSize;
            this.bufferManager = BufferManager.CreateBufferManager(bindingElement.MaxBufferPoolSize, maxBufferSize);

            var messageEncoderElement = context.BindingParameters
                                        .OfType <MessageEncodingBindingElement>()
                                        .SingleOrDefault()
                                        ?? new MtomMessageEncodingBindingElement();

            this.encoderFactory = messageEncoderElement.CreateMessageEncoderFactory();
        }
Exemple #8
0
        public static void Main(string[] args)
        {
            string[] splitArgs = null;
            if (args.Length != 1 || (splitArgs = args[0].Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries)).Length != 2)
            {
                Console.WriteLine("usage: EchoClient <hostname>:<port>");
                Console.WriteLine("example:");
                Console.WriteLine("    > EchoClient localhost:9211");
                Environment.Exit(-1);
            }

            var host = splitArgs[0];
            var port = int.Parse(splitArgs[1]);

            var cts           = new CancellationTokenSource();
            var bufferManager = BufferManager.CreateBufferManager(2 << 16, 2 << 8);

            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socket.Connect(host, port);

            var receiverDisposable = socket.ToFrameReceiver(SocketFlags.None, bufferManager)
                                     .SubscribeOn(TaskPoolScheduler.Default)
                                     .Subscribe(
                managedBuffer =>
            {
                Console.WriteLine("Read: " + Encoding.UTF8.GetString(managedBuffer.Buffer, 0, managedBuffer.Length));
                managedBuffer.Dispose();
            },
                error => Console.WriteLine("Error: " + error.Message),
                () => Console.WriteLine("OnCompleted: FrameReceiver"));

            var sender = socket.ToFrameSender(SocketFlags.None, cts.Token);

            var lineReader = Console.In.ToLineObservable();

            lineReader
            .Subscribe(
                line =>
            {
                var writeBuffer = Encoding.UTF8.GetBytes(line);
                sender.OnNext(new ManagedBuffer(writeBuffer, writeBuffer.Length, null));
            },
                error => Console.WriteLine("Error: " + error.Message),
                () => Console.WriteLine("OnCompleted: LineReader"));

            receiverDisposable.Dispose();

            cts.Cancel();
        }
Exemple #9
0
        public static void Main(string[] args)
        {
            var endpoint = ProgramArgs.Parse(args, new[] { "127.0.0.1:9211" }).EndPoint;

            var cts           = new CancellationTokenSource();
            var bufferManager = BufferManager.CreateBufferManager(2 << 16, 2 << 8);

            endpoint.ToConnectObservable()
            .ObserveOn(TaskPoolScheduler.Default)
            .Subscribe(socket =>
            {
                var frameClientSubject = socket.ToFrameClientSubject(SocketFlags.None, bufferManager, cts.Token);

                var observerDisposable =
                    frameClientSubject
                    .ObserveOn(TaskPoolScheduler.Default)
                    .Subscribe(
                        managedBuffer =>
                {
                    var buf = managedBuffer.Value;
                    if (buf.Array != null)
                    {
                        Console.WriteLine("Read: " + Encoding.UTF8.GetString(buf.Array, buf.Offset, buf.Count));
                    }
                    managedBuffer.Dispose();
                },
                        error => Console.WriteLine("Error: " + error.Message),
                        () => Console.WriteLine("OnCompleted: FrameReceiver"));

                Console.In.ToLineObservable()
                .Subscribe(
                    line =>
                {
                    var writeBuffer = Encoding.UTF8.GetBytes(line);
                    frameClientSubject.OnNext(DisposableValue.Create(new ArraySegment <byte>(writeBuffer), Disposable.Empty));
                },
                    error => Console.WriteLine("Error: " + error.Message),
                    () => Console.WriteLine("OnCompleted: LineReader"));
                cts.Token.WaitHandle.WaitOne();
                //Thread.Sleep(10*1000);
                observerDisposable.Dispose();

                cts.Cancel();
            },
                       error => Console.WriteLine("Failed to connect: " + error.Message),
                       cts.Token);

            cts.Token.WaitHandle.WaitOne();
        }
        /// <summary>
        /// Initializes a new instance of a TCP Frame Transmitter for DSPEx
        /// </summary>
        /// <param name="pipeName">
        /// The name of the pipe which we are writing to
        /// </param>
        public NamedPipeFrameTransmitter(string pipeName)
        {
            m_stream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
            m_stream.Connect();
            m_writer = new BinaryWriter(m_stream);

            // Elevate to DSPEx - this blocks until the byte has been written to the underlying stream.
            m_writer.Write((byte)DTP.DSPEX_INIT);

            m_bufferPool = BufferManager.CreateBufferManager(100000, DTPConstants.kMaxMessageSize);
            for (int i = 0; i < 100; i++)
            {
                m_bufferPool.ReturnBuffer(new byte[DTPConstants.kMaxMessageSize]);
            }
        }
        public UdpChannelListener(TransportBindingElement bindingElement, BindingContext context)
        {
            _BufferManager = BufferManager.CreateBufferManager(bindingElement.MaxBufferPoolSize, ExDefaultValue.MaxBufferSize);
            var me = context.BindingParameters.Find <MessageEncodingBindingElement>();

            if (me != null)
            {
                _MessageEncoderFactory = me.CreateMessageEncoderFactory();
            }

            _ChannelQueue             = new ExQueue <IInputChannel>();
            _CurrentChannelLockObject = new object();
            _Sockets = new List <Socket>(2);
            initializeUri(context);
        }
Exemple #12
0
        private static HandshakeDelegate BuildHandshakeDelegateForDispatcher(IServiceDispatcher dispatcher)
        {
            BindingElementCollection                  be     = dispatcher.Binding.CreateBindingElements();
            MessageEncodingBindingElement             mebe   = be.Find <MessageEncodingBindingElement>();
            MessageEncoderFactory                     mefact = mebe.CreateMessageEncoderFactory();
            ConnectionOrientedTransportBindingElement tbe    = be.Find <ConnectionOrientedTransportBindingElement>();
            int                   maxReceivedMessageSize     = (int)Math.Min(tbe.MaxReceivedMessageSize, int.MaxValue);
            int                   maxBufferSize          = tbe.MaxBufferSize;
            var                   bufferManager          = BufferManager.CreateBufferManager(tbe.MaxBufferPoolSize, maxReceivedMessageSize);
            int                   connectionBufferSize   = tbe.ConnectionBufferSize;
            TransferMode          transferMode           = tbe.TransferMode;
            var                   upgradeBindingElements = (from element in be where element is StreamUpgradeBindingElement select element).Cast <StreamUpgradeBindingElement>().ToList();
            StreamUpgradeProvider streamUpgradeProvider  = null;
            ISecurityCapabilities securityCapabilities   = null;

            if (upgradeBindingElements.Count > 1)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.MultipleStreamUpgradeProvidersInParameters));
            }
            // TODO: Limit NamedPipes to prevent it using SslStreamSecurityUpgradeProvider
            else if ((upgradeBindingElements.Count == 1) /*&& this.SupportsUpgrade(upgradeBindingElements[0])*/)
            {
                SecurityCredentialsManager credentialsManager = dispatcher.Host.Description.Behaviors.Find <SecurityCredentialsManager>();
                var bindingContext = new BindingContext(new CustomBinding(dispatcher.Binding), new BindingParameterCollection());

                if (credentialsManager != null)
                {
                    bindingContext.BindingParameters.Add(credentialsManager);
                }

                streamUpgradeProvider = upgradeBindingElements[0].BuildServerStreamUpgradeProvider(bindingContext);
                streamUpgradeProvider.OpenAsync().GetAwaiter().GetResult();
                securityCapabilities = upgradeBindingElements[0].GetProperty <ISecurityCapabilities>(bindingContext);
            }
            return((connection) =>
            {
                connection.MessageEncoderFactory = mefact;
                connection.StreamUpgradeAcceptor = streamUpgradeProvider?.CreateUpgradeAcceptor();
                connection.SecurityCapabilities = securityCapabilities;
                connection.ServiceDispatcher = dispatcher;
                connection.BufferManager = bufferManager;
                connection.MaxReceivedMessageSize = maxReceivedMessageSize;
                connection.MaxBufferSize = maxBufferSize;
                connection.ConnectionBufferSize = connectionBufferSize;
                connection.TransferMode = transferMode;
                return Task.CompletedTask;
            });
        }
        public void VerifyBufferPoolsCreatedtest()
        {
            for (int i = 80000; i <= 90000; i += 5000)
            {
                BufferManager bufferManager = BufferManager.CreateBufferManager(524288L, i);
                bool          flag          = BufferManagerTestsCommon.VerifyBufferPoolsCreated(bufferManager);
                testPassed &= flag;
                _output.WriteLine("Correct BufferPools are created for maxbuffersize:{0} {1} ", new object[]
                {
                    i,
                    flag
                });

                Assert.True(testPassed);
            }
        }
        public AsyncSocketClient(int _maxSize, int _maxConnnections, ICommonLog _logTool)
        {
            m_readWritePool   = new SocketAsyncEventArgsPool <AsyncClientToken>();
            m_maxConnnections = _maxConnnections;
            m_maxSize         = _maxSize;
            LogTool           = _logTool;
            m_bufferManager   = BufferManager.CreateBufferManager(m_maxConnnections * m_maxSize, m_maxSize);

            for (int i = 0; i < _maxConnnections; i++)
            {
                AsyncClientToken asyncClientToken = new AsyncClientToken();
                asyncClientToken.Buffer = m_bufferManager.TakeBuffer(m_maxSize);
                m_readWritePool.Push(asyncClientToken);
            }

            m_maxNumberAcceptedClients = new Semaphore(m_maxConnnections, m_maxConnnections);
        }
Exemple #15
0
        public void TestFinalise()
        {
            const int maxBufferPoolSize = 2 << 32;
            const int maxBufferSize     = 2 << 16;
            var       bufferManager     = BufferManager.CreateBufferManager(maxBufferPoolSize, maxBufferSize);

            const int len = 13;
            var       buf = bufferManager.TakeBuffer(len);

            var managedBuffer = new ManagedBuffer(buf, len, bufferManager);

            managedBuffer.Dispose();
            managedBuffer = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
Exemple #16
0
        static void Main(string[] args)
        {
            var endpoint = ProgramArgs.Parse(args, new[] { "127.0.0.1:9211" }).EndPoint;

            var cts           = new CancellationTokenSource();
            var bufferManager = BufferManager.CreateBufferManager(2 << 16, 2 << 8);

            endpoint.ToConnectObservable()
            .Subscribe(client =>
            {
                var frameClientSubject = client.ToFrameClientSubject(bufferManager, cts.Token);

                var observerDisposable =
                    frameClientSubject
                    .ObserveOn(TaskPoolScheduler.Default)
                    .Subscribe(
                        disposableBuffer =>
                {
                    Console.WriteLine("Read: " + Encoding.UTF8.GetString(disposableBuffer.Bytes, 0, disposableBuffer.Length));
                    disposableBuffer.Dispose();
                },
                        error => Console.WriteLine("Error: " + error.Message),
                        () => Console.WriteLine("OnCompleted: FrameReceiver"));

                Console.In.ToLineObservable()
                .Subscribe(
                    line =>
                {
                    var writeBuffer = Encoding.UTF8.GetBytes(line);
                    frameClientSubject.OnNext(new DisposableByteBuffer(writeBuffer, writeBuffer.Length, Disposable.Empty));
                },
                    error => Console.WriteLine("Error: " + error.Message),
                    () => Console.WriteLine("OnCompleted: LineReader"));

                observerDisposable.Dispose();

                cts.Cancel();
            },
                       error =>
            {
                Console.WriteLine("Failed to connect: " + error.Message);
                Environment.Exit(-1);
            });

            cts.Token.WaitHandle.WaitOne();
        }
Exemple #17
0
        /// <summary>
        /// Constructor for request factory.
        /// </summary>
        /// <param name="transportElement"></param>
        /// <param name="context"></param>
        public SerialRequestChannelFactory(
            SerialTransportBindingElement transportElement,
            BindingContext context)
            : base(context.Binding)
        {
            MessageEncodingBindingElement messageEncodingElement =
                context.RemainingBindingElements.Remove <MessageEncodingBindingElement>();

            this.bufferManager =
                BufferManager.CreateBufferManager(
                    transportElement.MaxBufferPoolSize, 0x400000); //4MB

            this.encoderFactory =
                messageEncodingElement.CreateMessageEncoderFactory();
            MaxReceivedMessageSize = transportElement.MaxReceivedMessageSize;
            this.PortNumber        = transportElement.FactoryPort;
        }
Exemple #18
0
        static void Main(string[] args)
        {
            var endpoint = ProgramArgs.Parse(args, new[] { "127.0.0.1:9211" }).EndPoint;

            var cts           = new CancellationTokenSource();
            var bufferManager = BufferManager.CreateBufferManager(2 << 16, 2 << 8);

            var selector = new Selector();

            Task.Factory.StartNew(() => selector.Dispatch(60000000, cts.Token), cts.Token);

            endpoint.ToConnectObservable(selector, cts.Token)
            .Subscribe(socket =>
            {
                var frameClientSubject = socket.ToFrameClientSubject(SocketFlags.None, bufferManager, selector, cts.Token);

                var observerDisposable =
                    frameClientSubject
                    .ObserveOn(TaskPoolScheduler.Default)
                    .Subscribe(
                        disposableBuffer =>
                {
                    Console.WriteLine("Read: " + Encoding.UTF8.GetString(disposableBuffer.Value.Array, 0, disposableBuffer.Value.Count));
                    disposableBuffer.Dispose();
                },
                        error => Console.WriteLine("Error: " + error.Message),
                        () => Console.WriteLine("OnCompleted: FrameReceiver"));

                Console.In.ToLineObservable()
                .Subscribe(
                    line =>
                {
                    var writeBuffer = Encoding.UTF8.GetBytes(line);
                    frameClientSubject.OnNext(DisposableValue.Create(new ArraySegment <byte>(writeBuffer, 0, writeBuffer.Length), Disposable.Empty));
                },
                    error => Console.WriteLine("Error: " + error.Message),
                    () => Console.WriteLine("OnCompleted: LineReader"));

                observerDisposable.Dispose();

                cts.Cancel();
            });

            cts.Token.WaitHandle.WaitOne();
        }
Exemple #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NmsInputChannelListener"/> class.
        /// </summary>
        /// <param name="transportElement">The binding element.</param>
        /// <param name="context">The context.</param>
        internal NmsInputChannelListener(NmsTransportBindingElement transportElement, BindingContext context)
            : base(context.Binding)
        {
            _bufferManager = BufferManager.CreateBufferManager(transportElement.MaxBufferPoolSize, (int)transportElement.MaxReceivedMessageSize);

            MessageEncodingBindingElement messageEncoderBindingElement = context.BindingParameters.Remove <MessageEncodingBindingElement>();

            _messageEncoderFactory = (messageEncoderBindingElement != null)
                                ? messageEncoderBindingElement.CreateMessageEncoderFactory()
                                : NmsConstants.DefaultMessageEncoderFactory;

            _channelQueue       = new InputQueue <IInputChannel>();
            _currentChannelLock = new object();
            _destinationName    = transportElement.Destination;
            _destinationType    = transportElement.DestinationType;
            _uri = new Uri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);
            Tracer.DebugFormat("Listening to {0} at {1}/{2}", _destinationType, _uri, _destinationName);
        }
Exemple #20
0
        protected static IEnumerable <DataWithRange> GetDataWithRangesToUpload(FileInfo vhdFile, UploadContextDisk context)
        {
            var uploadableRanges = context.UploadableRanges;
            var manager          = BufferManager.CreateBufferManager(Int32.MaxValue, MaxBufferSize);

            using (var vds = new VirtualDiskStream(vhdFile.FullName))
            {
                foreach (var range in uploadableRanges)
                {
                    var localRange = range;
                    yield return(new DataWithRange(manager)
                    {
                        Data = ReadBytes(vds, localRange, manager),
                        Range = localRange
                    });
                }
            }
            yield break;
        }
        // Simulates a message being sent from a client and received on a server
        public static Message SendAndReceiveMessage(Message toSend)
        {
            MessageEncoder encoder;

            if (toSend.Version.Envelope == EnvelopeVersion.Soap11)
            {
                encoder = new TextMessageEncodingBindingElement(toSend.Version, Encoding.UTF8).CreateMessageEncoderFactory().Encoder;
            }
            else
            {
                encoder = new BinaryMessageEncodingBindingElement().CreateMessageEncoderFactory().Encoder;
            }

            BufferManager       bufferManager  = BufferManager.CreateBufferManager(int.MaxValue, int.MaxValue);
            ArraySegment <byte> encodedMessage = encoder.WriteMessage(toSend, int.MaxValue, bufferManager);
            Message             r = encoder.ReadMessage(encodedMessage, bufferManager);

            return(r);
        }
        /// <summary>
        /// 初始化 SocketAsyncEventArgs 池, 并设置 SocketAsyncEventArgs.Buffer 缓存.
        /// </summary>
        /// <param name="capacity">初始状态容量大小</param>
        /// <param name="completed">SocketAsyncEventArgs.Completed 事件执行的方法</param>
        /// <param name="singleBufferMaxSize">SocketAsyncEventArgs.Buffer 的最大 Length, 默认为8K</param>
        public SocketAsyncEventArgsPool(int capacity, EventHandler <SocketAsyncEventArgs> completed, int singleBufferMaxSize = 8 * 1024)
        {
            socketAsyncCompleted     = completed;
            this.singleBufferMaxSize = singleBufferMaxSize;
            //缓存池大小与SocketAsyncEventArgs池大小相同,因为每个SocketAsyncEventArgs只用一个缓存
            bufferManager = BufferManager.CreateBufferManager(singleBufferMaxSize * capacity, singleBufferMaxSize);
            pool          = new ConcurrentStack <SocketAsyncEventArgs>();

            for (int i = 0; i < capacity; i++)
            {
                SocketAsyncEventArgs arg = TryCreateNew();

                if (arg == null)
                {
                    break;
                }

                pool.Push(arg);
            }
        }
Exemple #23
0
        /// <summary>
        /// Configure internal settings, it's the final call before usage
        /// </summary>
        public void FinishConfig()
        {
            if (_config._isSetBuffer)
            {
                // TakeBuffer expects a buffer of *at least* the specified size
                // thus we set the max single buffer a bit larger
                _bufferManager = BufferManager.CreateBufferManager(
                    _config._maxSingleBufSize * _config._maxPoolSize * _config._operationsToPreAlloc,
                    _config._maxSingleBufSize);
            }

            SaeaAwaitable args;
            var           size = _config._initPoolSize;

            for (int i = 0; i < size; i++)
            {
                args = CreateSaeaAwaitable();
                _argsPool.Add(args);
            }
        }
Exemple #24
0
        public HyperVNetChannelListener(HyperVNetBindingElement bindingElement, BindingContext context)
            : base(context.Binding)
        {
            // populate members from binding element
            this.maxBufferSize = (int)bindingElement.MaxReceivedMessageSize;
            this.bufferManager = BufferManager.CreateBufferManager(bindingElement.MaxBufferPoolSize, maxBufferSize);

            var messageEncoderBindingElement = context.BindingParameters.OfType <MessageEncodingBindingElement>().SingleOrDefault();

            if (messageEncoderBindingElement != null)
            {
                this.encoderFactory = messageEncoderBindingElement.CreateMessageEncoderFactory();
            }
            else
            {
                this.encoderFactory = new MtomMessageEncodingBindingElement().CreateMessageEncoderFactory();
            }

            this.Uri = new Uri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);
        }
Exemple #25
0
        internal HttpChannelFactory(HttpTransportBindingElement bindingElement, BindingContext context) : base(context.Binding)
        {
            this._bufferManager = BufferManager.CreateBufferManager(bindingElement.MaxBufferPoolSize, int.MaxValue);

            var messageEncoderBindingElements = context.BindingParameters.FindAll <MessageEncodingBindingElement>();

            if (messageEncoderBindingElements.Count > 1)
            {
                throw new InvalidOperationException("More than one MessageEncodingBindingElement was found in the BindingParameters of the BindingContext");
            }
            else if (messageEncoderBindingElements.Count == 1)
            {
                this._messageEncoderFactory = messageEncoderBindingElements[0].CreateMessageEncoderFactory();
            }
            else
            {
                this._messageEncoderFactory = CustomHttpConstants.DefaultMessageEncoderFactory;
            }
            _bindingElement = bindingElement;
        }
        internal UdpChannelListener(UdpTransportBindingElement bindingElement, BindingContext context)
            : base(context.Binding)
        {
            this.maxMessageSize    = (int)bindingElement.MaxReceivedMessageSize;
            this.multicast         = bindingElement.Multicast;
            this.bufferManager     = BufferManager.CreateBufferManager(bindingElement.MaxBufferPoolSize, this.maxMessageSize);
            this.maxBufferPoolSize = bindingElement.MaxBufferPoolSize;

            MessageEncodingBindingElement messageEncoderBindingElement = context.BindingParameters.Remove <MessageEncodingBindingElement>();

            if (messageEncoderBindingElement != null)
            {
                this.messageEncoderFactory = messageEncoderBindingElement.CreateMessageEncoderFactory();
            }
            else
            {
                this.messageEncoderFactory = UdpConstants.DefaultMessageEncoderFactory;
            }

            this.channelQueue       = new InputQueue <IInputChannel>();
            this.currentChannelLock = new object();

            Uri baseAddress = context.ListenUriBaseAddress;

            if (baseAddress == null)
            {
                if (context.ListenUriMode == ListenUriMode.Unique)
                {
                    UriBuilder uriBuilder = new UriBuilder(this.Scheme, Dns.GetHostEntry(String.Empty).HostName);
                    uriBuilder.Path = Guid.NewGuid().ToString();
                    baseAddress     = uriBuilder.Uri;
                }
                else
                {
                    throw new InvalidOperationException(
                              "Null is only a supported value for ListenUriBaseAddress when using ListenUriMode.Unique.");
                }
            }

            this.InitializeUri(baseAddress, context.ListenUriRelativeAddress, context.ListenUriMode);
        }
Exemple #27
0
        internal CustomHttpRequestChannel(CustomHttpChannelFactory factory,
                                          EndpointAddress to,
                                          Uri via,
                                          bool manualAddressing,
                                          MessageEncoder encoder,
                                          CustomHttpTransportBindingElement bindingElement)
            : base(factory)
        {
            if (!manualAddressing && (to == null))
            {
                throw new ArgumentNullException("to");
            }

            this._factory          = factory;
            this._to               = to;
            this._via              = via;
            this._encoder          = encoder;
            this._manualAddressing = manualAddressing;

            this.bufferManager = BufferManager.CreateBufferManager(bindingElement.MaxBufferPoolSize, (int)bindingElement.MaxReceivedMessageSize);
        }
Exemple #28
0
 public TableReplyChannelListener(BindingContext context, TableTransportBindingElement element) : base(context.Binding)
 {
     this.encoderFactory     = context.BindingParameters.Remove <MessageEncodingBindingElement>().CreateMessageEncoderFactory();
     this.bufferManager      = BufferManager.CreateBufferManager(element.MaxBufferPoolSize, int.MaxValue);
     this.targetPartitionKey = element.TargetPartitionKey;
     this.storageAccount     = CloudStorageAccount.Parse(element.ConnectionString);
     this.Uri          = new Uri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);
     this.replyChannel = new Lazy <TableReplyChannel>(
         () =>
     {
         var address = new EndpointAddress(this.Uri);
         return(new TableReplyChannel(
                    this,
                    this.storageAccount.CreateCloudTableClient(),
                    this.TableName,
                    this.targetPartitionKey,
                    this.bufferManager,
                    address,
                    this.encoderFactory.CreateSessionEncoder()));
     });
 }
Exemple #29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NmsChannelFactory&lt;TChannel&gt;"/> class.
        /// </summary>
        /// <param name="bindingElement">The binding element.</param>
        /// <param name="context">The context.</param>
        internal NmsChannelFactory(NmsTransportBindingElement bindingElement, BindingContext context)
            : base(context.Binding)
        {
            _bindingElement = bindingElement;

            Collection <MessageEncodingBindingElement> messageEncoderBindingElements = context.BindingParameters.FindAll <MessageEncodingBindingElement>();

            if (messageEncoderBindingElements.Count > 1)
            {
                throw new InvalidOperationException("More than one MessageEncodingBindingElement was found in the BindingParameters of the BindingContext");
            }
            _encoderFactory = (messageEncoderBindingElements.Count == 0)
                                ? NmsConstants.DefaultMessageEncoderFactory
                                : messageEncoderBindingElements[0].CreateMessageEncoderFactory();

            _bufferManager   = BufferManager.CreateBufferManager(bindingElement.MaxBufferPoolSize, Int32.MaxValue);
            _destination     = bindingElement.Destination;
            _destinationType = bindingElement.DestinationType;

            Tracer.DebugFormat("Destination ({0}) : {1}", _destinationType, _destination);
        }
        public AsyncSocketListener(int _maxSize, int _maxConnnections, ICommonLog _logTool)
        {
            m_readWritePool   = new SocketAsyncEventArgsPool <SocketAsyncEventArgs>();
            m_maxConnnections = _maxConnnections;
            m_maxSize         = _maxSize;
            LogTool           = _logTool;

            //m_bufferManager = BufferManager.CreateBufferManager(m_maxConnnections * m_maxSize * opsToPreAlloc, m_maxSize);
            m_bufferManager = BufferManager.CreateBufferManager(m_maxConnnections * m_maxSize, m_maxSize);

            for (int i = 0; i < m_maxConnnections; i++)
            {
                SocketAsyncEventArgs socketAsyncEventArg = new SocketAsyncEventArgs();
                socketAsyncEventArg.UserToken  = new T();
                socketAsyncEventArg.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed);
                socketAsyncEventArg.SetBuffer(m_bufferManager.TakeBuffer(m_maxSize), 0, m_maxSize);
                m_readWritePool.Push(socketAsyncEventArg);
            }

            m_maxNumberAcceptedClients = new Semaphore(m_maxConnnections, m_maxConnnections);
        }