Пример #1
0
        internal bool DumpCorrupttedData(ClientResponseContext context)
        {
            if (context.BytesTransferred == 0)
            {
                context.Clear();
                return(false);
            }

            if (this.Manager.Configuration.DumpCorruptResponse)
            {
#if !SILVERLIGHT
                using (var dumpStream = OpenDumpStream(context.SessionStartedAt, context.RemoteEndPoint, context.SessionId, MessageType.Response, context.MessageId))
#else
                using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
                    using (var dumpStream = OpenDumpStream(storage, context.SessionStartedAt, context.RemoteEndPoint, context.SessionId, MessageType.Response, context.MessageId))
#endif
                {
                    dumpStream.Write(context.CurrentReceivingBuffer, context.CurrentReceivingBufferOffset, context.BytesTransferred);
                    dumpStream.Flush();
                }
            }

            context.ShiftCurrentReceivingBuffer();

            return(true);
        }
        public void TestShiftCurrentReceivingBuffer_EqualToRemains_CurrentReceivingBufferOffsetIsInitializedAndBufferIsSwappedAndReceivedDataIsAppended()
        {
            int bytesTransferred = 13;
            var target           = new ClientResponseContext();
            var oldBuffer        = target.CurrentReceivingBuffer;

            target.SetBytesTransferred(bytesTransferred);
            target.ShiftCurrentReceivingBuffer();

            target.SetBytesTransferred(oldBuffer.Length - bytesTransferred);
            target.ShiftCurrentReceivingBuffer();
            Assert.That(target.CurrentReceivingBuffer, Is.Not.SameAs(oldBuffer));
            Assert.That(target.CurrentReceivingBufferOffset, Is.EqualTo(0));
            Assert.That(target.ReceivedData.Count, Is.EqualTo(2));
            Assert.That(target.ReceivedData[1].Array, Is.EqualTo(oldBuffer));
            Assert.That(target.ReceivedData[1].Offset, Is.EqualTo(bytesTransferred));
            Assert.That(target.ReceivedData[1].Count, Is.EqualTo(oldBuffer.Length - bytesTransferred));
        }
        public void TestShiftCurrentReceivingBuffer_LessThanRemains_CurrentReceivingBufferOffsetIsShifttedAndReceivedDataIsAppended()
        {
            int bytesTransferred = 13;
            var target           = new ClientResponseContext();

            target.SetBytesTransferred(bytesTransferred);
            target.ShiftCurrentReceivingBuffer();
            Assert.That(target.CurrentReceivingBufferOffset, Is.EqualTo(bytesTransferred));
            Assert.That(target.ReceivedData.Count, Is.EqualTo(1));
            Assert.That(target.ReceivedData[0].Array, Is.EqualTo(target.CurrentReceivingBuffer));
            Assert.That(target.ReceivedData[0].Offset, Is.EqualTo(0));
            Assert.That(target.ReceivedData[0].Count, Is.EqualTo(bytesTransferred));
        }
 private static void MakeBufferDirty(ClientResponseContext target)
 {
     target.SetTransport(new DummyClientTransport());
     target.SetReceivingBuffer(new byte[] { 1, 2, 3, 4 });
     target.SetBytesTransferred(1);
     target.ShiftCurrentReceivingBuffer();
     target.ErrorBuffer    = new ByteArraySegmentStream(CreateDirtyBytes());
     target.ErrorStartAt   = 1;
     target.HeaderUnpacker = Unpacker.Create(new MemoryStream());
     target.MessageId      = 1;
     target.NextProcess    = _ => true;
     target.ReceivedData.Add(new ArraySegment <byte>(new byte[] { 1, 2, 3, 4 }));
     target.ResultBuffer  = new ByteArraySegmentStream(CreateDirtyBytes());
     target.ResultStartAt = 2;
     target.RenewSessionId();
     target.UnpackingBuffer = new ByteArraySegmentStream(CreateDirtyBytes());
 }
		internal bool DumpCorrupttedData( ClientResponseContext context )
		{
			if ( context.BytesTransferred == 0 )
			{
				context.Clear();
				return false;
			}

			if ( this.Manager.Configuration.DumpCorruptResponse )
			{
#if !SILVERLIGHT
				using ( var dumpStream = OpenDumpStream( context.SessionStartedAt, context.RemoteEndPoint, context.SessionId, MessageType.Response, context.MessageId ) )
#else
				using( var storage = IsolatedStorageFile.GetUserStoreForApplication() )
				using( var dumpStream = OpenDumpStream( storage, context.SessionStartedAt, context.RemoteEndPoint, context.SessionId, MessageType.Response, context.MessageId ) )
#endif
				{
					dumpStream.Write( context.CurrentReceivingBuffer, context.CurrentReceivingBufferOffset, context.BytesTransferred );
					dumpStream.Flush();
				}
			}

			context.ShiftCurrentReceivingBuffer();

			return true;
		}
        /// <summary>
        ///		Called when asynchronous 'Receive' operation is completed.
        /// </summary>
        /// <param name="context">Context information.</param>
        ///	<exception cref="InvalidOperationException">
        ///		This instance is not in 'Idle' nor 'Receiving' state.
        ///	</exception>
        ///	<exception cref="ObjectDisposedException">
        ///		This instance is disposed.
        ///	</exception>
        protected virtual void OnReceived(ClientResponseContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            Contract.EndContractBlock();

            if (MsgPackRpcClientProtocolsTrace.ShouldTrace(MsgPackRpcClientProtocolsTrace.ReceiveInboundData))
            {
                var socket = this.BoundSocket;
                MsgPackRpcClientProtocolsTrace.TraceEvent(
                    MsgPackRpcClientProtocolsTrace.ReceiveInboundData,
                    "Receive response. {{ \"SessionID\" : {0}, \"Socket\" : 0x{1:X}, \"RemoteEndPoint\" : \"{2}\", \"LocalEndPoint\" : \"{3}\", \"BytesTransfered\" : {4} }}",
                    context.SessionId,
                    GetHandle(socket),
                    GetRemoteEndPoint(socket, context),
                    GetLocalEndPoint(socket),
                    context.BytesTransferred
                    );
            }

            if (context.BytesTransferred == 0)
            {
                if (Interlocked.CompareExchange(ref this._shutdownSource, ( int )ShutdownSource.Server, 0) == 0)
                {
                    // Server sent shutdown response.
                    this.ShutdownReceiving();

                    // recv() returns 0 when the server socket shutdown gracefully.
                    var socket = this.BoundSocket;
                    MsgPackRpcClientProtocolsTrace.TraceEvent(
                        MsgPackRpcClientProtocolsTrace.DetectServerShutdown,
                        "Server shutdown current socket. {{ \"Socket\" : 0x{0:X}, \"RemoteEndPoint\" : \"{1}\", \"LocalEndPoint\" : \"{2}\" }}",
                        GetHandle(socket),
                        GetRemoteEndPoint(socket, context),
                        GetLocalEndPoint(socket)
                        );
                }
                else if (this.IsClientShutdown)
                {
                    // Client was started shutdown.
                    this.ShutdownReceiving();
                }

                if (!context.ReceivedData.Any(segment => 0 < segment.Count))
                {
                    // There are no data to handle.
                    this.FinishReceiving(context);
                    return;
                }
            }
            else
            {
                context.ShiftCurrentReceivingBuffer();
            }

            if (MsgPackRpcClientProtocolsTrace.ShouldTrace(MsgPackRpcClientProtocolsTrace.DeserializeResponse))
            {
                MsgPackRpcClientProtocolsTrace.TraceEvent(
                    MsgPackRpcClientProtocolsTrace.DeserializeResponse,
                    "Deserialize response. {{ \"SessionID\" : {0}, \"Length\" : {1} }}",
                    context.SessionId,
                    context.ReceivedData.Sum(item => ( long )item.Count)
                    );
            }

            // Go deserialization pipeline.

            // Exceptions here means message error.
            try
            {
                ApplyFilters(this._beforeDeserializationFilters, context);
            }
            catch (RpcException ex)
            {
                this.HandleDeserializationError(context, TryDetectMessageId(context), new RpcErrorMessage(ex.RpcError, ex.Message, ex.DebugInformation), "Filter rejects message.", () => context.ReceivedData.SelectMany(s => s.AsEnumerable()).ToArray());
                this.FinishReceiving(context);
                return;
            }

            if (!context.NextProcess(context))
            {
                if (this.IsServerShutdown)
                {
                    this.ShutdownReceiving();
                }
                else if (this.CanResumeReceiving)
                {
                    // Wait to arrive more data from server.
                    this.ReceiveCore(context);
                    return;
                }

                this.FinishReceiving(context);
                return;
            }
        }