private static async Task <bool> ReadBytesAsync(this Stream stream, byte[] buffer, int offset, int length, Stream dest) { var bytes = await stream.ReadBytesAsync(buffer, offset, length).ConfigureAwait(false); var len = bytes.Length; dest.Write(bytes, 0, len); return(len == offset + length); }
private static void readPayloadDataAsync( Stream stream, WebSocketFrame frame, Action <WebSocketFrame> completed, Action <Exception> error) { var len = frame.FullPayloadLength; if (len == 0) { frame._payloadData = new PayloadData(WebSocket.EmptyBytes, frame.IsMasked); completed(frame); return; } // Check if allowable length. if (len > PayloadData.MaxLength) { throw new WebSocketException( CloseStatusCode.TooBig, "The length of 'Payload Data' of a frame is greater than the allowable max length."); } Action <byte[]> compl = bytes => { if (bytes.LongLength != (long)len) { throw new WebSocketException( "The 'Payload Data' of a frame cannot be read from the data source."); } frame._payloadData = new PayloadData(bytes, frame.IsMasked); completed(frame); }; if (frame._payloadLength < 127) { stream.ReadBytesAsync((int)len, compl, error); return; } stream.ReadBytesAsync((long)len, 1024, compl, error); }
public static async Task <IpcMessage> ParseAsync(Stream stream, CancellationToken cancellationToken) { IpcMessage message = new IpcMessage(); message.Header = await IpcHeader.ParseAsync(stream, cancellationToken).ConfigureAwait(false); message.Payload = await stream.ReadBytesAsync(message.Header.Size - IpcHeader.HeaderSizeInBytes, cancellationToken).ConfigureAwait(false); return(message); }
private static void readPayloadDataAsync( Stream stream, WebSocketFrame frame, Action <WebSocketFrame> completed, Action <Exception> error) { var len = frame.FullPayloadLength; if (len == 0) { frame._payloadData = PayloadData.Empty; completed(frame); return; } if (len > PayloadData.MaxLength) { throw new WebSocketException(CloseStatusCode.TooBig, "A frame has a long payload length."); } var llen = (long)len; Action <byte[]> compl = bytes => { if (bytes.Length != llen) { throw new WebSocketException( "The payload data of a frame cannot be read from the stream."); } frame._payloadData = new PayloadData(bytes, llen); completed(frame); }; if (frame._payloadLength < 127) { stream.ReadBytesAsync((int)len, compl, error); return; } stream.ReadBytesAsync(llen, 1024, compl, error); }
public static async Task <IpcHeader> ParseAsync(Stream stream, CancellationToken cancellationToken) { byte[] buffer = await stream.ReadBytesAsync(HeaderSizeInBytes, cancellationToken).ConfigureAwait(false); using MemoryStream bufferStream = new MemoryStream(buffer); using BinaryReader bufferReader = new BinaryReader(bufferStream); IpcHeader header = Parse(bufferReader); Debug.Assert(bufferStream.Position == bufferStream.Length); return(header); }
private static async Task <byte[]> ReadEntityBodyAsync(Stream stream, string length, CancellationToken ct) { long len; if (!long.TryParse(length, out len)) { throw new ArgumentException("Cannot be parsed.", nameof(length)); } if (len < 0) { throw new ArgumentOutOfRangeException(nameof(length), "Less than zero."); } return(len > 1024 ? await stream.ReadBytesAsync(len, 1024, ct) : len > 0 ? await stream.ReadBytesAsync((int)len, ct) : null); }
/// <summary> /// Read 1 byte from the stream /// </summary> /// <param name="stream"></param> /// <returns></returns> internal static async Task <Option <byte> > ReadByteAsync(this Stream stream) { var data = await stream.ReadBytesAsync(1); if (data.HasValue(out var value) && value.Length == 1) { return(Some(value[0])); } return(None <byte>()); }
public override async Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckDebug.NotNull(buffer); if (!hasRead) { hasRead = true; VerifyZlibHeader(await stream.ReadBytesAsync(2)); } return(await base.ReadAsync(buffer, offset, count, cancellationToken)); }
internal static async Task <WebSocketFrame> ReadAsync(Stream stream, bool unmask) { var header = await stream.ReadBytesAsync(2).ConfigureAwait(false); if (header.Length != 2) { throw new WebSocketException( "The header part of a frame cannot be read from the data source."); } return(await ReadAsync(header, stream, unmask).ConfigureAwait(false)); }
public static async Task<VInt> ReadUIntAsync(Stream s, CancellationToken cancel_token) { int first = await s.ReadByteAsync(); if (first<0) throw new EndOfStreamException(); int len = CheckLength(first); var bin = new byte[len]; bin[0] = (byte)first; await s.ReadBytesAsync(bin, 1, len-1, cancel_token); long res = bin.Aggregate(0L, (r, b) => (r<<8) | b); res &= (1<<(7*len))-1; return new VInt(res, bin); }
public async Task <byte[]> AttachStream(Stream stream, bool disposeOld = false) { if (disposeOld) { _stream?.Dispose(); } var headerBuffer = new byte[9]; await stream.ReadBytesAsync(headerBuffer); _stream = stream; return(headerBuffer); }
internal static async Task <Byte[]> ToArrayAsync(this Stream stream) { var ms = stream as MemoryStream; if (ms != null) { return(ms.ToArray()); } stream.Position = 0; return(await stream.ReadBytesAsync()); }
public override async Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (firstReadWrite) { firstReadWrite = false; // Chop off the first two bytes var b1b2 = await stream.ReadBytesAsync(2); } return(await base.ReadAsync(buffer, offset, count, cancellationToken)); }
public static async Task <SocksProxyNegotiationReply> ReadRequestAsync(Stream s) { SocksProxyNegotiationReply reply = new SocksProxyNegotiationReply(); byte[] buffer = new byte[2]; await s.ReadBytesAsync(buffer, 0, buffer.Length); reply._version = buffer[0]; reply._method = (SocksProxyAuthenticationMethod)buffer[1]; return(reply); }
public static async Task <SocksProxyAuthenticationReply> ReadRequestAsync(Stream s) { SocksProxyAuthenticationReply reply = new SocksProxyAuthenticationReply(); byte[] buffer = new byte[2]; await s.ReadBytesAsync(buffer, 0, buffer.Length); reply._version = buffer[0]; reply._status = buffer[1] == 0 ? SocksProxyAuthenticationStatus.Success : SocksProxyAuthenticationStatus.Failure; return(reply); }
static async Task <(uint echoTime, Space <byte> echoRandom)> ReadS2Async(Stream stream) { var buffer = await stream.ReadBytesAsync(FrameLength); var reader = new AmfReader(buffer, EmptyContext); var time = reader.ReadUInt32(); // "time": a copy of c1 time var ____ = reader.ReadUInt32(); // "time2": current local time var echo = reader.ReadSpan(RandomLength); // "random echo": a copy of c1 random return(time, echo); }
internal static async Task <SubscribeAck> ReadSubscribeAckAsync(this Stream stream) { var remainingLength = await DecodeRemainingLengthAsync(stream).ConfigureAwait(false); var buffer = new byte[remainingLength]; await stream.ReadBytesAsync(buffer, 0, remainingLength).ConfigureAwait(false); return(new SubscribeAck { PacketId = buffer.FromBigEndianBytes(), ReturnCodes = new ArraySegment <byte>(buffer, WordSize, remainingLength - WordSize).ToArray() }); }
private static async Task ValidateGCDump(Stream gcdumpStream) { using CancellationTokenSource cancellation = new(CommonTestTimeouts.GCDumpTimeout); byte[] buffer = await gcdumpStream.ReadBytesAsync(24, cancellation.Token); const string knownHeaderText = "!FastSerialization.1"; Encoding enc8 = Encoding.UTF8; string headerText = enc8.GetString(buffer, 4, knownHeaderText.Length); Assert.Equal(knownHeaderText, headerText); }
internal static async Task <bool> ReadExpectedBuffer(this Stream stream, byte[] expected) { try { var bytes = await stream.ReadBytesAsync(expected.Length).ConfigureAwait(false); return(expected.SequenceEqual(bytes)); } catch (Exception) { return(false); } }
static async Task <(uint three, uint time, uint zero, Space <byte> random)> ReadS1Async(Stream stream) { var buffer = await stream.ReadBytesAsync(C1Length); var reader = new AmfReader(buffer, EmptyContext); var three = reader.ReadByte(); // rtmp version (constant 3) [s0] var time = reader.ReadUInt32(); // time [s1] var zero = reader.ReadUInt32(); // zero [s1] var random = reader.ReadSpan(RandomLength); // random bytes [s1] return(three, time, zero, random); }
public static async Task <SocksProxyRequest> ReadRequestAsync(Stream s) { SocksProxyRequest request = new SocksProxyRequest(); byte[] buffer = new byte[3]; await s.ReadBytesAsync(buffer, 0, 3); request._version = buffer[0]; request._command = (SocksProxyRequestCommand)buffer[1]; request._dstEP = await SocksProxyServer.ReadEndPointAsync(s); return(request); }
public async Task <byte[]> SendRequestAsync(string resource, RestResponseFormat format, params string[] parms) { WebRequest request = BuildHttpRequest(resource, format, parms); using (WebResponse response = await GetWebResponseAsync(request).ConfigureAwait(false)) { Stream stream = response.GetResponseStream(); int bytesToRead = (int)response.ContentLength; byte[] buffer = await stream.ReadBytesAsync(bytesToRead).ConfigureAwait(false); return(buffer); } }
public static async Task Receive(Stream stream, IReceiverCallback callback, Uri uri) { Envelope[] messages = null; try { var lengthBytes = await stream.ReadBytesAsync(sizeof(int)); var length = BitConverter.ToInt32(lengthBytes, 0); if (length == 0) { return; } var bytes = await stream.ReadBytesAsync(length); messages = Envelope.ReadMany(bytes); } catch (Exception e) { await callback.Failed(e, messages); await stream.SendBuffer(SerializationFailureBuffer); return; } try { await receive(stream, callback, messages, uri); } catch (Exception ex) { await callback.Failed(ex, messages); await stream.SendBuffer(ProcessingFailureBuffer); } }
private async Task <MessageHeader> ReadHeader(CancellationToken ct = default) { byte[] headerBuffer = null; byte[] timestampBuffer = null; try { headerBuffer = _arrayPool.Rent(15); timestampBuffer = _arrayPool.Rent(4); await _stream.ReadBytesAsync(headerBuffer.AsMemory(0, 15), ct); var type = (MessageType)headerBuffer[4]; var length = NetworkBitConverter.ToUInt24(headerBuffer.AsSpan(5, 3)); headerBuffer.AsSpan(8, 3).CopyTo(timestampBuffer.AsSpan(1)); timestampBuffer[0] = headerBuffer[11]; var timestamp = NetworkBitConverter.ToInt32(timestampBuffer.AsSpan(0, 4)); var streamId = NetworkBitConverter.ToUInt24(headerBuffer.AsSpan(12, 3)); var header = new MessageHeader() { MessageLength = length, MessageStreamId = streamId, MessageType = type, Timestamp = (uint)timestamp }; return(header); } finally { if (headerBuffer != null) { _arrayPool.Return(headerBuffer); } if (timestampBuffer != null) { _arrayPool.Return(timestampBuffer); } } }
public static async Task <SocksProxyReply> ReadReplyAsync(Stream s) { SocksProxyReply reply = new SocksProxyReply(); byte[] buffer = new byte[3]; await s.ReadBytesAsync(buffer, 0, 3); reply._version = buffer[0]; reply._reply = (SocksProxyReplyCode)buffer[1]; reply._bindEP = await SocksProxyServer.ReadEndPointAsync(s); return(reply); }
protected override async Task ProcessInternalAsync(Stream stream) { _logger.Debug("Reading acknowledgement about accepting messages to {0}", _endpoint); var recieveBuffer = new byte[ProtocolConstants.AcknowledgedBuffer.Length]; await stream.ReadBytesAsync(recieveBuffer, "receive confirmation", false).ConfigureAwait(false); var recieveRespone = Encoding.Unicode.GetString(recieveBuffer); if (recieveRespone != ProtocolConstants.Acknowledged) { _logger.Info("Response from sender acknowledgement was the wrong format", _endpoint); throw new InvalidAcknowledgementException(); } }
private static void readHeaderAsync( Stream stream, Action <WebSocketFrame> completed, Action <Exception> error ) { stream.ReadBytesAsync( 2, bytes => { var frame = processHeader(bytes); completed(frame); }, error ); }
protected override async Task <int> GetInternalAsync(Stream stream) { var lenOfDataToReadBuffer = new byte[sizeof(int)]; await stream.ReadBytesAsync(lenOfDataToReadBuffer, "length data", false).ConfigureAwait(false); var lengthOfDataToRead = BitConverter.ToInt32(lenOfDataToReadBuffer, 0); if (lengthOfDataToRead < 0) { throw new InvalidLengthException(string.Format("Got invalid length {0} from endpoint {1}", lengthOfDataToRead, _endpoint)); } return(lengthOfDataToRead); }
public static async Task <T> ReadJsonAsync <T>(this Stream stream, JsonConverter[] converters, CancellationToken cancellation = default) { byte[] buffer = await stream.ReadBytesAsync(4, cancellation); // Skip until a valid JSON message is reached byte[] expected = Encoding.UTF8.GetBytes("JSON"); while (!expected.SequenceEqual(buffer)) { Console.WriteLine($"Skipping byte, current buffer value is '{Encoding.UTF8.GetString(buffer)}'."); // Shift buffer down for (int i = 0; i < buffer.Length; i++) { buffer[i] = buffer[i + 1]; } // Read an additional byte into the buffer byte[] newByte = await stream.ReadBytesAsync(1, cancellation); buffer[buffer.Length - 1] = newByte[0]; } // Get length buffer = await stream.ReadBytesAsync(4, cancellation); int length = BitConverter.ToInt32(buffer, 0); // Get JSON data buffer = await stream.ReadBytesAsync(length, cancellation); string rawData = Encoding.UTF8.GetString(buffer); Console.WriteLine($"Message received: '{rawData}'."); // Deserialize the raw data return(JsonConvert.DeserializeObject <T>(rawData, converters)); }
public static async Task Receive(ITransportLogger logger, Stream stream, IListeningWorkerQueue callback, Uri uri) { Envelope[] messages = null; try { var lengthBytes = await stream.ReadBytesAsync(sizeof(int)); var length = BitConverter.ToInt32(lengthBytes, 0); if (length == 0) { return; } var bytes = await stream.ReadBytesAsync(length); messages = Envelope.ReadMany(bytes); } catch (Exception e) { logger.LogException(new MessageFailureException(messages, e)); await stream.SendBuffer(SerializationFailureBuffer); return; } try { await receive(logger, stream, callback, messages, uri); } catch (Exception ex) { logger.LogException(new MessageFailureException(messages, ex)); await stream.SendBuffer(ProcessingFailureBuffer); } }
internal static async Task <WebSocketFrame> ReadFrameAsync(Stream stream, bool unmask = false) { var frame = ProcessHeader(await stream.ReadBytesAsync(2)); await ReadExtendedPayloadLengthAsync(stream, frame); await ReadMaskingKeyAsync(stream, frame); await ReadPayloadDataAsync(stream, frame); if (unmask) { frame.Unmask(); } return(frame); }
protected override async Task ProcessInternalAsync(Stream stream) { var buffer = new byte[ProtocolConstants.RevertBuffer.Length]; try { await stream.ReadBytesAsync(buffer, "revert", true); } catch (Exception) { //a revert was not sent, send is complete return; } var revert = Encoding.Unicode.GetString(buffer); if (revert == ProtocolConstants.Revert) { throw new RevertSendException(); } }
public async Task<bool> ReadTagBodyAsync(Stream stream, CancellationToken cancel_token) { this.Body = await stream.ReadBytesAsync(this.DataSize, cancel_token); this.Footer = await stream.ReadBytesAsync(4, cancel_token); return IsValidFooter; }
/// <summary> /// Sends a binary data from the specified <see cref="Stream"/> /// using the WebSocket connection. /// </summary> /// <remarks> /// This method does not wait for the send to be complete. /// </remarks> /// <param name="stream"> /// A <see cref="Stream"/> object from which contains a binary data to send. /// </param> /// <param name="length"> /// An <see cref="int"/> that contains the number of bytes to send. /// </param> /// <param name="completed"> /// An Action<bool> delegate that references the method(s) called when /// the send is complete. /// A <see cref="bool"/> passed to this delegate is <c>true</c> if the send is /// complete successfully; otherwise, <c>false</c>. /// </param> public void Send(Stream stream, int length, Action<bool> completed) { var msg = _readyState.CheckIfOpen () ?? stream.CheckIfCanRead () ?? (length < 1 ? "'length' must be greater than 0." : null); if (msg != null) { _logger.Error (msg); error (msg); return; } stream.ReadBytesAsync ( length, data => { var len = data.Length; if (len == 0) { var err = "A data cannot be read from 'stream'."; _logger.Error (err); error (err); return; } if (len < length) _logger.Warn (String.Format ( "A data with 'length' cannot be read from 'stream'.\nexpected: {0} actual: {1}", length, len)); var sent = len <= FragmentLength ? send (Opcode.BINARY, data) : send (Opcode.BINARY, new MemoryStream (data)); if (completed != null) completed (sent); }, ex => { _logger.Fatal (ex.ToString ()); error ("An exception has occurred."); }); }
/// <summary> /// Sends binary data from the specified <see cref="Stream"/> asynchronously using /// the WebSocket connection. /// </summary> /// <remarks> /// This method doesn't wait for the send to be complete. /// </remarks> /// <param name="stream"> /// A <see cref="Stream"/> from which contains the binary data to send. /// </param> /// <param name="length"> /// An <see cref="int"/> that represents the number of bytes to send. /// </param> /// <param name="completed"> /// An <c>Action<bool></c> delegate that references the method(s) called when /// the send is complete. A <see cref="bool"/> passed to this delegate is <c>true</c> /// if the send is complete successfully. /// </param> public void SendAsync (Stream stream, int length, Action<bool> completed) { var msg = _readyState.CheckIfAvailable (false, true, false, false) ?? CheckSendParameters (stream, length); if (msg != null) { _logger.Error (msg); error ("An error has occurred in sending the data.", null); return; } stream.ReadBytesAsync ( length, data => { var len = data.Length; if (len == 0) { _logger.Error ("The data cannot be read from 'stream'."); error ("An error has occurred in sending the data.", null); return; } if (len < length) _logger.Warn ( String.Format ( "The data with 'length' cannot be read from 'stream':\n expected: {0}\n actual: {1}", length, len)); var sent = send (Opcode.Binary, new MemoryStream (data)); if (completed != null) completed (sent); }, ex => { _logger.Fatal (ex.ToString ()); error ("An exception has occurred while sending the data.", ex); }); }
public async Task ReadAsync( Stream stream, IRTMPContentSink sink, CancellationToken cancel_token) { int len = 0; var bin = new byte[13]; try { len += await stream.ReadBytesAsync(bin, len, 13-len, cancel_token); } catch (EndOfStreamException) { return; } var header = new FileHeader(bin); if (!header.IsValid) throw new BadDataException(); sink.OnFLVHeader(); len = 0; bool eos = false; while (!eos) { try { len += await stream.ReadBytesAsync(bin, len, 11-len, cancel_token); var read_valid = false; var body = new FLVTag(this, bin); if (body.IsValidHeader) { if (await body.ReadTagBodyAsync(stream, cancel_token)) { len = 0; read_valid = true; switch (body.Type) { case FLVTag.TagType.Audio: sink.OnAudio(body.ToRTMPMessage()); break; case FLVTag.TagType.Video: sink.OnVideo(body.ToRTMPMessage()); break; case FLVTag.TagType.Script: sink.OnData(new DataAMF0Message(body.ToRTMPMessage())); break; } } } else { len += await stream.ReadBytesAsync(bin, len, 13-len, cancel_token); var new_header = new FileHeader(bin); if (new_header.IsValid) { read_valid = true; sink.OnFLVHeader(); } } if (!read_valid) { int pos = 1; for (; pos<len; pos++) { var b = bin[pos]; if ((b & 0xC0)==0 && ((b & 0x1F)==8 || (b & 0x1F)==9 || (b & 0x1F)==18)) { break; } } if (pos==len) { len = 0; } else { Array.Copy(bin, pos, bin, 0, len-pos); len -= pos; } } } catch (EndOfStreamException) { eos = true; } } }
/// <summary> /// Sends binary data from the specified <see cref="Stream"/> asynchronously using /// the WebSocket connection. /// </summary> /// <remarks> /// This method doesn't wait for the send to be complete. /// </remarks> /// <param name="stream"> /// A <see cref="Stream"/> from which contains the binary data to send. /// </param> /// <param name="length"> /// An <see cref="int"/> that represents the number of bytes to send. /// </param> /// <param name="completed"> /// An <c>Action<bool></c> delegate that references the method(s) called when /// the send is complete. A <see cref="bool"/> passed to this delegate is <c>true</c> /// if the send is complete successfully. /// </param> public void SendAsync(Stream stream, int length, Action<bool> completed) { var msg = CheckIfAvailable(_readyState, false, true, false, false) ?? CheckSendParameters(stream, length); if (msg != null) { #if COMPAT Log.Error(msg); #else msg.Error(); #endif Error("An error has occurred in sending data.", null); return; } stream.ReadBytesAsync( length, data => { var len = data.Length; if (len == 0) { #if COMPAT Log.Error("The data cannot be read from 'stream'."); #endif Error("An error has occurred in sending data.", null); return; } #if COMPAT if (len < length) Log.InfoFormat( "The length of the data is less than 'length':\n expected: {0}\n actual: {1}", length, len); #endif var sent = send(Opcode.Binary, new MemoryStream(data)); completed?.Invoke(sent); }, ex => { Error("An exception has occurred while sending data.", ex); } ); }
public async Task ReadBodyAsync(Stream s, CancellationToken cancel_token) { if (this.Size.IsUnknown) return; this.Data = await s.ReadBytesAsync((int)this.Size.Value, cancel_token); }
/// <summary> /// Sends a binary data from the specified <see cref="Stream"/> asynchronously /// using the WebSocket connection. /// </summary> /// <remarks> /// This method doesn't wait for the send to be complete. /// </remarks> /// <param name="stream"> /// A <see cref="Stream"/> from which contains the binary data to send. /// </param> /// <param name="length"> /// An <see cref="int"/> that represents the number of bytes to send. /// </param> /// <param name="completed"> /// An <c>Action<bool></c> delegate that references the method(s) called when /// the send is complete. A <see cref="bool"/> passed to this delegate is <c>true</c> /// if the send is complete successfully. /// </param> public void SendAsync (Stream stream, int length, Action<bool> completed) { var msg = _readyState.CheckIfOpen () ?? stream.CheckIfCanRead () ?? (length < 1 ? "'length' is less than 1." : null); if (msg != null) { _logger.Error (msg); error ("An error has occurred in sending the data.", null); return; } stream.ReadBytesAsync ( length, data => { var len = data.Length; if (len == 0) { _logger.Error ("The data cannot be read from 'stream'."); error ("An error has occurred in sending the data.", null); return; } if (len < length) _logger.Warn ( String.Format ( "The data with 'length' cannot be read from 'stream'.\nexpected: {0} actual: {1}", length, len)); var sent = send (Opcode.Binary, new MemoryStream (data)); if (completed != null) completed (sent); }, ex => { _logger.Fatal (ex.ToString ()); error ("An exception has occurred while sending the data.", ex); }); }
/// <summary> /// Sends binary data from the specified <see cref="Stream"/> asynchronously to /// every client in the WebSocket service. /// </summary> /// <remarks> /// This method doesn't wait for the send to be complete. /// </remarks> /// <param name="stream"> /// A <see cref="Stream"/> from which contains the binary data to send. /// </param> /// <param name="length"> /// An <see cref="int"/> that represents the number of bytes to send. /// </param> /// <param name="completed"> /// An <see cref="Action"/> delegate that references the method(s) called when /// the send is complete. /// </param> public void BroadcastAsync(Stream stream, int length, Action completed) { var msg = _state.CheckIfAvailable (false, true, false) ?? stream.CheckIfCanRead () ?? (length < 1 ? "'length' is less than 1." : null); if (msg != null) { _logger.Error (msg); return; } stream.ReadBytesAsync ( length, data => { var len = data.Length; if (len == 0) { _logger.Error ("The data cannot be read from 'stream'."); return; } if (len < length) _logger.Warn ( String.Format ( "The data with 'length' cannot be read from 'stream':\n expected: {0}\n actual: {1}", length, len)); if (len <= WebSocket.FragmentLength) broadcast (Opcode.Binary, data, completed); else broadcast (Opcode.Binary, new MemoryStream (data), completed); }, ex => _logger.Fatal (ex.ToString ())); }
/// <summary> /// Broadcasts a binary data from the specified <see cref="Stream"/> /// to all clients of a WebSocket service. /// </summary> /// <remarks> /// This method does not wait for the broadcast to be complete. /// </remarks> /// <param name="stream"> /// A <see cref="Stream"/> object from which contains a binary data to broadcast. /// </param> /// <param name="length"> /// An <see cref="int"/> that contains the number of bytes to broadcast. /// </param> /// <param name="completed"> /// A <see cref="Action"/> delegate that references the method(s) called when /// the broadcast is complete. /// </param> public void Broadcast (Stream stream, int length, Action completed) { var msg = _state.CheckIfStarted () ?? stream.CheckIfCanRead () ?? (length < 1 ? "'length' must be greater than 0." : null); if (msg != null) { _logger.Error (msg); return; } stream.ReadBytesAsync ( length, data => { var len = data.Length; if (len == 0) { _logger.Error ("A data cannot be read from 'stream'."); return; } if (len < length) _logger.Warn (String.Format ( "A data with 'length' cannot be read from 'stream'.\nexpected: {0} actual: {1}", length, len)); if (len <= WebSocket.FragmentLength) Broadcast (Opcode.BINARY, data, completed); else Broadcast (Opcode.BINARY, new MemoryStream (data), completed); }, ex => { _logger.Fatal (ex.ToString ()); }); }