Example #1
0
        private static async Task <KelinciData> ReadKelinciDataAsync(NetworkStream stream, CancellationToken token)
        {
            byte[] mode   = new byte[1];
            byte[] length = new byte[4];
            try
            {
                //Read first Byte   ==> Mode
                int  bytesRead = stream.Read(mode, 0, 1);
                bool success   = (bytesRead == 1);
                Logger.Trace("{0} Mode bytes read", bytesRead);
                //Read next 4 Bytes ==> Length
                bytesRead = stream.Read(length, 0, 4);
                success   = success && (bytesRead == 4);
                Logger.Trace("{0} Length bytes read", bytesRead);
                //Read Bytes        ==> Data
                byte[] data = new byte[StaticHelper.ConvertLittleEndian(length)];

                int i = 0;
                while ((i != data.Length) && (!token.IsCancellationRequested))
                {
                    i += await stream.ReadAsync(data, i, data.Length - i, token);
                }

                if (success)
                {
                    return(new KelinciData(StaticHelper.ConvertLittleEndian(mode), StaticHelper.ConvertLittleEndian(length), data));
                }
                throw new IOException("ReadKelinciData failed");
            }
            catch (Exception e)
            {
                Logger.Error("Exception: {0}", e.ToString());
                return(null);
            }
        }