public static async Task <WebSocketMessageContext> ToBinaryContextAsync(this WebSocketReceiveResult result, IStreamCompressor compressor, byte[] input) { if (result == null) { throw new ArgumentNullException(nameof(result)); } var content = input.Split(); byte[] header = content.Item1; byte[] body = content.Item2; var webSocketContext = new WebSocketMessageContext(); bool isCompressed = GZipHelper.IsGZipBody(body); if (isCompressed) { body = await compressor.DeCompressAsync(body); } using (var ms = new MemoryStream(header)) using (var sr = new StreamReader(ms)) { var data = await sr.ReadToEndAsync(); if (data != null) { try { webSocketContext.Header = JsonConvert.DeserializeObject <Dictionary <string, object> >(data); } catch (Exception ex) { webSocketContext.Header = new Dictionary <string, object> { ["Exception"] = ex.Message, ["Unknown"] = "Unknown binary message!" }; } } } using (var ms = new MemoryStream(body)) using (var sr = new StreamReader(ms)) { var data = await sr.ReadToEndAsync(); webSocketContext.Value = data; } webSocketContext.Length = input.Length; webSocketContext.MessageType = WebSocketMessageType.Binary; webSocketContext.Command = WebSocketCommands.DataSend; return(webSocketContext); }
private async Task <byte[]> PrepareFramesBytesAsync(byte[] body, IDictionary <string, object> properties) { if (body == null) { throw new ArgumentNullException(nameof(body)); } if (properties == null) { properties = new Dictionary <string, object>(); } bool compressed = GZipHelper.IsGZipBody(body); object key = null; if (properties.TryGetValue(CompressedKey, out key)) { properties[CompressedKey] = compressed; } else { properties.Add(CompressedKey, compressed); } string props = JsonConvert.SerializeObject(properties); byte[] header = Encoding.UTF8.GetBytes($"{props}"); #if DEBUG if (properties.TryGetValue("Key", out key)) { int length = body.Length; Debug.WriteLine($"=====Key: {key?.ToString()}=====Length: {length}====="); } #endif if (!compressed) { body = await _compressor.CompressAsync(body); } body = header.Concat(Splitter).Concat(body).ToArray(); return(body); }
private async Task <byte[]> ToBytesAsync(byte[] body, IDictionary <string, object> properties = null) { if (body == null) { throw new ArgumentNullException(nameof(body)); } if (properties == null) { properties = new Dictionary <string, object>(); } bool compressed = GZipHelper.IsGZipBody(body); if (properties.TryGetValue(NCSConstants.CompressedKey, out object key)) { properties[NCSConstants.CompressedKey] = compressed; } else { properties.Add(NCSConstants.CompressedKey, compressed); } _headerProvider.Invoke(properties); string props = JsonConvert.SerializeObject(properties); byte[] header = Encoding.UTF8.GetBytes(props); if (!compressed) { body = await _compressor.CompressAsync(body); } body = header.Concat(NCSConstants.Splitter).Concat(body).ToArray(); return(body); }