Exemple #1
0
        public void MessageReceivedCallback(IAsyncResult result)
        {
            ITransferContext context   = (ITransferContext)result.AsyncState;
            MarkupType       noiseKind = MarkupType.None;

            int receive = context.Listener.EndReceive(result);

            if (receive > 0)
            {
                noiseKind = context.IncomingMessage(receive);
            }

            if (context.DeserialPacketSize > 0)
            {
                int buffersize = (context.DeserialPacketSize < context.BufferSize) ? (int)context.DeserialPacketSize : context.BufferSize;
                context.Listener.BeginReceive(context.MessageBuffer, 0, buffersize, SocketFlags.None, MessageReceivedCallback, context);
            }
            else
            {
                object received     = context.DeserialPacket;
                object readPosition = context.DeserialPacketId;

                if (noiseKind == MarkupType.Block || (noiseKind == MarkupType.End && (int)readPosition < (context.Transfer.HeaderReceived.Context.ObjectsCount - 1)))
                {
                    context.Listener.BeginReceive(context.MessageBuffer, 0, context.BufferSize, SocketFlags.None, MessageReceivedCallback, context);
                }

                TransferOperation request = new TransferOperation(context.Transfer, MessagePart.Message, DirectionType.Receive);
                request.Resolve(received, readPosition);

                if (context.ObjectsLeft <= 0 && !context.BatchesReceivedNotice.SafeWaitHandle.IsClosed)
                {
                    context.BatchesReceivedNotice.Set();
                }

                if (noiseKind == MarkupType.End && (int)readPosition >= (context.Transfer.HeaderReceived.Context.ObjectsCount - 1))
                {
                    context.BatchesReceivedNotice.WaitOne();
                    context.MessageReceivedNotice.Set();

                    try
                    {
                        MessageReceived.Execute(context);
                    }
                    catch (Exception ex)
                    {
                        Echo(ex.Message);
                        CloseClient(context.Id);
                    }
                }
            }
        }