public async Task <int> ReadInt32(CancellationToken cancellationToken = default) { using (var binaryReader = new AsyncBinaryReader(this.stream, true)) { var numBytes = await binaryReader.ReadIntAsync(cancellationToken).ConfigureAwait(false); if (numBytes != 4) { throw new InvalidOperationException("Expected to receive 4 bytes but got " + numBytes); } return(await binaryReader.ReadIntAsync(cancellationToken).ConfigureAwait(false)); } }
/// <summary> /// Reads the object using asynchronous methods. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A hot running task that returns the read object. /// </returns> public async Task <byte[]> ReadBytes(CancellationToken cancellationToken = default) { using (var binaryReader = new AsyncBinaryReader(this.stream, true)) { var msgLength = await binaryReader.ReadIntAsync(cancellationToken).ConfigureAwait(false); if (msgLength == 0) { return(null); } var bytes = await binaryReader.ReadBytesAsync(msgLength, cancellationToken).ConfigureAwait(false); return(bytes); } }
/// <summary> /// Reads the object using asynchronous methods. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A hot running task that returns the read object. /// </returns> public async Task <string> ReadString(CancellationToken cancellationToken = default) { using (var binaryReader = new AsyncBinaryReader(this.stream, true)) { var msgLength = await binaryReader.ReadIntAsync(cancellationToken).ConfigureAwait(false); if (msgLength == 0) { return(null); } var bytes = await binaryReader.ReadBytesAsync(msgLength, cancellationToken).ConfigureAwait(false); return(System.Text.Encoding.UTF8.GetString(bytes)); } }
/// <summary> /// Reads the object using asynchronous methods. /// </summary> /// <typeparam name="T">The type of parameter.</typeparam> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A hot running task that returns the read object. /// </returns> public async Task <T> Read <T>(CancellationToken cancellationToken = default) { using (var binaryReader = new AsyncBinaryReader(this.stream, true)) { var msgLength = await binaryReader.ReadIntAsync(cancellationToken).ConfigureAwait(false); if (msgLength == 0) { return(default(T)); } var jsonString = await binaryReader.ReadStringAsync(msgLength, Encoding.UTF8, cancellationToken).ConfigureAwait(false); return(JsonConvert.DeserializeObject <T>(jsonString, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto })); } }