Esempio n. 1
0
        public void ReceiveData(byte[] data)
        {
            if (data == null)
            {
                logger.Error("received null data");
                return;
            }

            // get length data
            if (this.bufferPos == -1)
            {
                if (data.Length != 4)
                {
                    logger.ErrorFormat("error length data. [{0}]", data.Length);
                    return;
                }

                // length data
                this.expectLen  = BitConverter.ToInt32(data, 0);
                this.recvBuffer = new byte[this.expectLen];
                this.bufferPos  = 0;

                return;
            }

            // fill buffer
            Array.Copy(data, 0, this.recvBuffer, this.bufferPos, data.Length);
            this.bufferPos += data.Length;
            if (this.bufferPos < this.expectLen)
            {
                return; // not full
            }
            this.bufferPos = -1;

            lock (this.recvLocker)
            {
                // complete the read async result
                if (this.readDataAsyncResultQueue.Count > 0)
                {
                    ReadDataAsyncResultServer result = this.readDataAsyncResultQueue.Dequeue();
                    if (data != null)
                    {
                        result.Complete(false, this.recvBuffer);
                    }
                    else
                    {
                        result.Complete(new TimeoutException());
                    }

                    return;
                }

                // there is no read data async result, cache the received data
                this.receivedDataQueue.Enqueue(this.recvBuffer);
            }
        }
Esempio n. 2
0
        public IAsyncResult BeginReceive(TimeSpan timeout, AsyncCallback callback, object state)
        {
            ReadDataAsyncResultServer result = new ReadDataAsyncResultServer(this, callback, state);

            lock (this.recvLocker)
            {
                // if there is already data received, complete the read async result immediately
                if (this.receivedDataQueue.Count > 0)
                {
                    result.Complete(true, this.receivedDataQueue.Dequeue());

                    return(result);
                }

                // there is no data received, wait for data arrive
                this.readDataAsyncResultQueue.Enqueue(result);
            }

            return(result);
        }