private void ReadCallback(IAsyncResult ar) { byte[] rcb = ( byte[] )ar.AsyncState; int bytes_read = _channel.EndReceive(ar); ConsoleOutput.Trace("ReadCallback: " + bytes_read); // copy to circular reading buffer _buffer.Write(rcb, bytes_read); // if has more data while (_buffer.Size() >= _next_size) { // is not waiting for data? if (_next_size == 0) // == 0 means data length is not detected. { if (_buffer.Size() >= Constant.SIZE_OF_INT) { byte[] sb = _buffer.Read(Constant.SIZE_OF_INT); _next_size = ByteConverter.BytesToInt(sb); } else { break; } } // is waiting for data? if (_next_size > 0) { // has enough data? if (_buffer.Size() >= _next_size) { byte[] b = _buffer.Read(_next_size); _listener.OnRead(_channel, b); ConsoleOutput.Trace("OnRead: " + b.Length); _next_size = 0; // == 0 means data length is not detected. } } } // continue reading _channel.BeginReceive (rcb, 0, rcb.Length , SocketFlags.None , new AsyncCallback(ReadCallback) , rcb); }