예제 #1
0
        public async Task AttributeMockSerializeDeserializeTest(int count, bool useParallel)
        {
            var serializer   = new TcpSerializer <AttributeMockSerialize>(_bitConverterHelper, i => new byte[i]);
            var deserializer = new TcpDeserializer <uint, AttributeMockSerialize>(_bitConverterHelper);

            var mock = new AttributeMockSerialize
            {
                Id          = TestContext.CurrentContext.Random.NextUInt(),
                DateTime    = DateTime.Now.AddSeconds(TestContext.CurrentContext.Random.NextUInt()),
                LongNumbers = TestContext.CurrentContext.Random.NextULong(),
                IntNumbers  = TestContext.CurrentContext.Random.NextUInt()
            };

            mock.BuildBody();

            var enumerable = Enumerable.Range(0, count);

            var tasks = (useParallel ? enumerable.AsParallel().Select(Selector) : enumerable.Select(Selector)).ToArray();

            await Task.WhenAll(tasks);

            Task Selector(int i) =>
            Task.Run(() =>
            {
                var serialize = serializer.Serialize(mock);
                _             = deserializer.Deserialize(new ReadOnlySequence <byte>(serialize.Request));
            });
        }
예제 #2
0
        public void Ctor()
        {
            _arrayPool = ArrayPool <byte> .Create();

            var helper = new BitConverterHelper(TcpClientIoOptions.Default.RegisterConverter(new TcpUtf8StringConverter()));

            _serializer   = new TcpSerializer <Mock>(helper, l => _arrayPool.Rent(l));
            _deserializer = new TcpDeserializer <long, Mock>(helper);
        }
예제 #3
0
        public void SerializeDeserializeTest()
        {
            var       ethalon             = Mock.Default();
            const int ethalonHeaderLength = 270;

            var serializer   = new TcpSerializer <Mock>(_bitConverterHelper, i => new byte[i]);
            var deserializer = new TcpDeserializer <long, Mock>(_bitConverterHelper);
            var serialize    = serializer.Serialize(ethalon);

            Assert.IsTrue(serialize.Request.Length == ethalon.Size + ethalonHeaderLength);
            var(_, deserialize) = deserializer.Deserialize(new ReadOnlySequence <byte>(serialize.Request));
            Assert.IsTrue(ethalon.Equals(deserialize));
        }
예제 #4
0
        public async Task SerializeDeserializeFromPipeReaderTest()
        {
            var       ethalon             = Mock.Default();
            const int ethalonHeaderLength = 270;

            var serializer   = new TcpSerializer <Mock>(_bitConverterHelper, i => new byte[i]);
            var deserializer = new TcpDeserializer <long, Mock>(_bitConverterHelper);
            var serialize    = serializer.Serialize(ethalon);

            Assert.IsTrue(serialize.Request.Length == ethalon.Size + ethalonHeaderLength);
            var(_, deserialize) = await deserializer.DeserializeAsync(PipeReader.Create(new MemoryStream(serialize.Request.ToArray())), CancellationToken.None);

            Assert.IsTrue(ethalon.Equals(deserialize));
        }
예제 #5
0
        public async Task SerializeDeserializeRecursiveComposeValueTypeTest()
        {
            var pool = ArrayPool <byte> .Create();

            var serializer   = new TcpSerializer <RecursiveMock <int> >(_bitConverterHelper, i => pool.Rent(i));
            var deserializer = new TcpDeserializer <long, RecursiveMock <int> >(_bitConverterHelper);
            var mock         = RecursiveMock <int> .Create(1337);

            var serialize = serializer.Serialize(mock);
            var pipe      = PipeReader.Create(new MemoryStream(serialize.Request.ToArray()));

            var(id, data) = await deserializer.DeserializeAsync(pipe, CancellationToken.None);

            Assert.NotNull(id);
            Assert.NotNull(data);
        }
예제 #6
0
        public async Task SerializeDeserializeSpeedTest()
        {
            var pool = ArrayPool <byte> .Create();

            var serializer   = new TcpSerializer <RecursiveMock <RecursiveMock <RecursiveMock <RecursiveMock <RecursiveMock <int> > > > > >(_bitConverterHelper, i => pool.Rent(i));
            var deserializer = new TcpDeserializer <long, RecursiveMock <RecursiveMock <RecursiveMock <RecursiveMock <RecursiveMock <int> > > > > >(_bitConverterHelper);
            var mock         = RecursiveMock <RecursiveMock <RecursiveMock <RecursiveMock <RecursiveMock <int> > > > > .Create(
                RecursiveMock <RecursiveMock <RecursiveMock <RecursiveMock <int> > > > .Create(
                    RecursiveMock <RecursiveMock <RecursiveMock <int> > > .Create(
                        RecursiveMock <RecursiveMock <int> > .Create(
                            RecursiveMock <int> .Create(int.MaxValue
                                                        )
                            )
                        )
                    )
                );

            var sw = Stopwatch.StartNew();

            SerializedRequest serialize = null;

            for (var i = 0; i < 10000; i++)
            {
                serialize = serializer.Serialize(mock);
            }

            sw.Stop();
            Assert.Less(sw.ElapsedMilliseconds, 1000);
            TestContext.WriteLine($"Serialize: {sw.Elapsed.ToString()}");
            sw.Reset();

            for (var i = 0; i < 10000; i++)
            {
                var pipe = PipeReader.Create(new MemoryStream(serialize.Request.ToArray()));
                sw.Start();
                var(id, data) = await deserializer.DeserializeAsync(pipe, CancellationToken.None);

                sw.Stop();
                Assert.NotNull(id);
                Assert.NotNull(data);
            }

            Assert.Less(sw.ElapsedMilliseconds, 1000);
            TestContext.WriteLine($"Deserialize: {sw.Elapsed.ToString()}");
        }
        private TcpClientIo(TcpClientIoOptions tcpClientIoOptions, ILogger <TcpClientIo <TId, TRequest, TResponse> > logger)
        {
            var pipe = new Pipe();

            Id          = Guid.NewGuid();
            _logger     = logger;
            _options    = tcpClientIoOptions ?? TcpClientIoOptions.Default;
            _batchRules = TcpBatchRules <TResponse> .Default;
            _baseCancellationTokenSource = new CancellationTokenSource();
            _baseCancellationToken       = _baseCancellationTokenSource.Token;
            _bufferBlockRequests         = new BufferBlock <SerializedRequest>();
            var middleware = new MiddlewareBuilder <ITcpBatch <TResponse> >()
                             .RegisterCancellationActionInWait((tcs, hasOwnToken) =>
            {
                if (_disposing || hasOwnToken)
                {
                    tcs.TrySetCanceled();
                }
                else if (!_disposing && _pipelineReadEnded)
                {
                    tcs.TrySetException(TcpClientIoException.ConnectionBroken());
                }
            })
                             .RegisterDuplicateActionInSet((batch, newBatch) => _batchRules.Update(batch, newBatch.Single()))
                             .RegisterCompletionActionInSet(() => _consumingResetEvent.Set());

            _completeResponses = new WaitingDictionary <TId, ITcpBatch <TResponse> >(middleware);
            _arrayPool         = ArrayPool <byte> .Create();

            var bitConverterHelper = new BitConverterHelper(_options);

            _serializer            = new TcpSerializer <TRequest>(bitConverterHelper, length => _arrayPool.Rent(length));
            _deserializer          = new TcpDeserializer <TId, TResponse>(bitConverterHelper);
            _writeResetEvent       = new AsyncManualResetEvent();
            _readResetEvent        = new AsyncManualResetEvent();
            _consumingResetEvent   = new AsyncManualResetEvent();
            _deserializePipeReader = pipe.Reader;
            _deserializePipeWriter = pipe.Writer;
        }