Beispiel #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));
            });
        }
Beispiel #2
0
 public WatcherWindow(IPAddress address, int port = 2000)
 {
     _pictureStream = new MemoryStream();
     _client        = new TcpSerializer(address, port);
     InitializeComponent();
     SubscribeToUpdates();
 }
        public void NotFoundConverterExceptionTest()
        {
            var serializer = new TcpSerializer <Mock>(new BitConverterHelper(new TcpClientIoOptions()), i => new byte[i]);
            var mock       = Mock.Default();

            Assert.Catch <TcpException>(() => serializer.Serialize(mock));
        }
Beispiel #4
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);
        }
        /// <summary>
        /// Called when a new client connects. Wraps the socket in a <see cref="TcpSerializer"/> and attaches it to a <see cref="ScreenRecorder"/> and a <see cref="RemoteControlCommandSubscription"/>.
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        protected override TcpConnection Accept(Socket socket)
        {
            var client = new TcpSerializer(socket);

            Recorder = new ScreenRecorder(client);
            Recorder.StartRecording();

            RemoteControl = new RemoteControlCommandSubscription(client);
            client.StartListening();

            return(client);
        }
        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));
        }
        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));
        }
        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);
        }
        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()}");
        }
        public void SerializeRecursiveComposeTypeTest()
        {
            var pool = ArrayPool <byte> .Create();

            var serializer = new TcpSerializer <RecursiveMock <RecursiveMock <RecursiveMock <RecursiveMock <MockOnlyMetaData> > > > >(_bitConverterHelper, i => pool.Rent(i));
            var mock       = RecursiveMock <RecursiveMock <RecursiveMock <RecursiveMock <MockOnlyMetaData> > > > .Create(
                RecursiveMock <RecursiveMock <RecursiveMock <MockOnlyMetaData> > > .Create(
                    RecursiveMock <RecursiveMock <MockOnlyMetaData> > .Create(
                        RecursiveMock <MockOnlyMetaData> .Create(
                            new MockOnlyMetaData()
                            )
                        )
                    )
                );

            var serializedRequest = serializer.Serialize(mock);

            serializedRequest.ReturnRentedArrays(pool, false);
        }
        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;
        }
Beispiel #12
0
 /// <summary>
 /// Initializes a new <see cref="RemoteControlCommandSubscription"/> and subscribes to messages coming from the provided connection
 /// </summary>
 /// <param name="connection">Connection to listen for messages on.</param>
 public RemoteControlCommandSubscription(TcpSerializer connection)
 {
     _connection        = connection;
     connection.OnData += HandleOnData;
 }
Beispiel #13
0
 public async ValueTask SendPingAsync()
 {
     var pingPacket    = GetPingPacket();
     var packageToSend = TcpSerializer.Serialize(pingPacket);
     await SocketStream.WriteAsync(packageToSend);
 }
Beispiel #14
0
 /// <summary>
 /// Creates a new <see cref="ScreenRecorder"/> instance.
 /// </summary>
 /// <param name="client">Target to write frames to</param>
 public ScreenRecorder(TcpSerializer client)
 {
     _client    = client;
     _isRunning = false;
 }