Пример #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Connection"/> class.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="textEncoding">The text encoding.</param>
        /// <param name="newLineSequence">The new line sequence used for read and write operations.</param>
        /// <param name="disableContinuousReading">if set to <c>true</c> [disable continuous reading].</param>
        /// <param name="blockSize">Size of the block. -- set to 0 or less to disable.</param>
        public Connection(
            TcpClient client,
            Encoding textEncoding,
            string newLineSequence,
            bool disableContinuousReading,
            int blockSize)
        {
            // Setup basic properties
            Id           = Guid.NewGuid();
            TextEncoding = textEncoding ?? throw new ArgumentNullException(nameof(textEncoding));

            // Setup new line sequence
            if (string.IsNullOrEmpty(newLineSequence))
            {
                throw new ArgumentException("Argument cannot be null", nameof(newLineSequence));
            }

            _newLineSequence             = newLineSequence;
            _newLineSequenceBytes        = TextEncoding.GetBytes(_newLineSequence);
            _newLineSequenceChars        = _newLineSequence.ToCharArray();
            _newLineSequenceLineSplitter = new[] { _newLineSequence };

            // Setup Connection timers
            ConnectionStartTimeUtc  = DateTime.UtcNow;
            DataReceivedLastTimeUtc = ConnectionStartTimeUtc;
            DataSentLastTimeUtc     = ConnectionStartTimeUtc;

            // Setup connection properties
            RemoteClient   = client ?? throw new ArgumentNullException(nameof(client));
            LocalEndPoint  = client.Client.LocalEndPoint as IPEndPoint;
            NetworkStream  = RemoteClient.GetStream();
            RemoteEndPoint = RemoteClient.Client.RemoteEndPoint as IPEndPoint;

            // Setup buffers
            _receiveBuffer        = new byte[RemoteClient.ReceiveBufferSize * 2];
            ProtocolBlockSize     = blockSize;
            _receiveBufferPointer = 0;

            // Setup continuous reading mode if enabled
            if (disableContinuousReading)
            {
                return;
            }

            ThreadPool.GetAvailableThreads(out var availableWorkerThreads, out _);
            ThreadPool.GetMaxThreads(out var maxWorkerThreads, out _);

            var activeThreadPoolTreads = maxWorkerThreads - availableWorkerThreads;

            if (activeThreadPoolTreads < Environment.ProcessorCount / 4)
            {
                ThreadPool.QueueUserWorkItem(PerformContinuousReading, this);
            }
            else
            {
                new Thread(PerformContinuousReading)
                {
                    IsBackground = true
                }.Start();
            }
        }