Task IGangMember.ConnectAsync( IGangController controller, Func <Task> _onDisconnectAsync) { return(Task.Run(async() => { do { using var data = new MemoryStream(); WebSocketReceiveResult result; do { result = await _webSocket .ReceiveAsync(_buffer, CancellationToken.None); if (result.MessageType != WebSocketMessageType.Binary) { break; } await data.WriteAsync(_buffer.AsMemory(0, result.Count)); } while (!result.EndOfMessage); if (data.Length > 0) { await controller.ReceiveAsync(data.ToArray()); } } while (_webSocket.State == WebSocketState.Open); if (_onDisconnectAsync != null) { await _onDisconnectAsync(); } })); }
private async Task <WebSocketReceiveResult> ReceiveAsyncCore(ArraySegment <byte> buffer, CancellationToken cancellationToken) { try { Memory <byte> bufferMemory = buffer.AsMemory(); using (MemoryHandle pinBuffer = bufferMemory.Pin()) { var receiveTask = BrowserInterop.ReceiveUnsafeSync(_innerWebSocket !, pinBuffer, bufferMemory.Length); if (receiveTask == null) { // return synchronously return(ConvertResponse()); } var wrappedTask = CancelationHelper(receiveTask, cancellationToken, _state); await wrappedTask.ConfigureAwait(true); return(ConvertResponse()); } } catch (OperationCanceledException) { throw; } catch (JSException ex) { if (ex.Message.StartsWith("InvalidState:")) { throw new WebSocketException(WebSocketError.InvalidState, SR.Format(SR.net_WebSockets_InvalidState, State, "Open, CloseSent"), ex); } throw new WebSocketException(WebSocketError.NativeError, ex); } }
public void TestRowArgbArraySegment() { using (var surface = new Surface(32, 16)) { var memory = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 120, 144, 23, 255, 78, 65, 113, 255, 0, 0 }; var expected = new ArraySegment <byte>(memory, 8, 8); surface.SetRowArgb(expected, 17, 9); var actual = new byte[expected.Count]; _ = surface.GetRowArgb(actual, 17, 9); CollectionAssert.AreEqual(expected.AsMemory().ToArray(), actual); } }
public static void ArraySegmentAsMemoryWithStartAndLength(int length, int start, int subLength) { const int segmentOffset = 5; int[] a = new int[length + segmentOffset]; ArraySegment <int> segment = new ArraySegment <int>(a, segmentOffset, length); Memory <int> m = segment.AsMemory(start, subLength); Assert.Equal(subLength, m.Length); if (subLength != 0) { m.Span[0] = 42; Assert.Equal(42, a[segmentOffset + start]); } }
public void TestMixArgbArraySegment() { var x = new byte[] { 0, 0, 120, 200, 40, 255, 240, 60, 32, 255, 0, 0 }; var y = new byte[] { 0, 0, 0, 0, 40, 110, 80, 255, 150, 74, 109, 255 }; var z = new byte[x.Length + 4]; var xs = new ArraySegment <byte>(x, 2, 8); var ys = new ArraySegment <byte>(y, 4, 8); var zs = new ArraySegment <byte>(z, 3, 8); var mixed = new byte[] { 104, 182, 48, 255, 222, 62, 47, 255 }; xs.MixArgb(ys, zs, 0.2f); CollectionAssert.AreEqual(mixed, zs.AsMemory().ToArray()); }
/// <summary> /// Gets densities for segments with size equal to <paramref name="segmentSize"/> /// </summary> /// <param name="buckets">Array of buckets</param> /// <param name="start">Start timestamp of the event range we want to find. If null, then it is a first event time in the first bucket of the buckets array.</param> /// <param name="segmentSize">Length/duration of one segment</param> /// <param name="finalize">Flag indicating that density should be calculated for the last incomplete segment if there is one</param> /// <param name="nextBatchStartTime">Next start time</param> /// <returns></returns> public static double[] GetDensities(ArraySegment <Bucket> bucketsArray, long?start, long segmentSize, bool finalize, out long nextBatchStartTime) { var buckets = bucketsArray.AsSpan(); if (buckets.Length < 1) { throw new ArgumentException("Empty array of buckets is not allowed"); } if (!start.HasValue) { start = buckets[0].GetAbsoluteTimeForEvent(buckets[0].GetFirstEvent()); } long end = buckets[buckets.Length - 1].GetAbsoluteTimeForEvent(buckets[buckets.Length - 1].GetLastEvent()) + 1; ushort totalSegments = 0; try { if (finalize) { totalSegments = checked ((ushort)Math.Ceiling((end - start.Value) / (double)segmentSize)); } else { totalSegments = checked ((ushort)Math.Floor((end - start.Value) / (double)segmentSize)); } } catch (OverflowException) { throw new ArgumentException("Too small segment size for such a big range", nameof(segmentSize)); } var densitiesBuf = new double[totalSegments]; DensityCalculator.CalculateDensities( bucketsArray.AsMemory(), new DensityCalculationRequest(start.Value, end, segmentSize), densitiesBuf, finalize, out long processedRange ); nextBatchStartTime = start.Value + processedRange; return(densitiesBuf); }
public static async IAsyncEnumerable <byte> ToAsyncEnumerable( this Stream stream, ArraySegment <byte> buffer, [EnumeratorCancellation] CancellationToken cancellationToken ) { // Validate parameters. if (stream == null) { throw new ArgumentNullException(nameof(stream)); } // Iterate through everything. await foreach (byte b in stream.ToAsyncEnumerable(buffer.AsMemory(), cancellationToken)) { yield return(b); } }
/// <summary> /// Appends a <see cref="ReadOnlyMemory{T}"/> of bytes to the end of the segment /// </summary> /// <param name="writerOffset"></param> /// <param name="bytes"></param> /// <param name="segment"></param> public static void Append(ArraySegment <byte> segment, ref int writerOffset, ReadOnlyMemory <byte> bytes) { if (segment.Array == null) { throw new ArgumentNullException(nameof(segment)); } var length = bytes.Length; MemoryMarshal.Write(segment.AsSpan(writerOffset), ref length); writerOffset += sizeof(int); if (bytes.Length > 0) { bytes.CopyTo(segment.AsMemory(writerOffset)); writerOffset += bytes.Length; } }
public void TestGetRowArgbArraySegment() { using (var bitmap = LoadResource("style.png")) using (var surface = LoadSurface(bitmap)) { var segment = new Rectangle(17, 4, 24, 1); var expected = new byte[segment.Width * 4]; var data = bitmap.LockBits(segment, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); data.GetRowArgb(expected, 0, 0); bitmap.UnlockBits(data); var memory = new byte[expected.Length + 32]; var actual = new ArraySegment <byte>(memory, 16, expected.Length); _ = surface.GetRowArgb(actual, segment.X, segment.Y); CollectionAssert.AreEqual(expected, actual.AsMemory().ToArray()); } }
private static async Task <JsonDocument> ParseAsyncCore( Stream utf8Json, JsonReaderOptions readerOptions = default, CancellationToken cancellationToken = default) { ArraySegment <byte> drained = await ReadToEndAsync(utf8Json, cancellationToken).ConfigureAwait(false); try { return(Parse(drained.AsMemory(), readerOptions, drained.Array)); } catch { // Holds document content, clear it before returning it. drained.AsSpan().Clear(); ArrayPool <byte> .Shared.Return(drained.Array); throw; } }
/// <summary> /// Parse a <see cref="Stream"/> as UTF-8-encoded data representing a single JSON value into a /// JsonDocument. The Stream will be read to completion. /// </summary> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="options">Options to control the reader behavior during parsing.</param> /// <returns> /// A JsonDocument representation of the JSON value. /// </returns> /// <exception cref="JsonException"> /// <paramref name="utf8Json"/> does not represent a valid single JSON value. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="options"/> contains unsupported options. /// </exception> public static JsonDocument Parse(Stream utf8Json, JsonDocumentOptions options = default) { if (utf8Json == null) { throw new ArgumentNullException(nameof(utf8Json)); } ArraySegment <byte> drained = ReadToEnd(utf8Json); try { return(Parse(drained.AsMemory(), options.GetReaderOptions(), drained.Array)); } catch { // Holds document content, clear it before returning it. drained.AsSpan().Clear(); ArrayPool <byte> .Shared.Return(drained.Array); throw; } }
/// <summary> /// Read bytes from TIFF file source. /// </summary> /// <param name="offset">The offset in the file.</param> /// <param name="buffer">The buffer to hold bytes.</param> /// <returns>The count of bytes read from file.</returns> public virtual int Read(TiffStreamOffset offset, ArraySegment <byte> buffer) => Read(offset, buffer.AsMemory());
private async void Initialize() { clientWebsocket = new ClientWebSocket(); Uri url = new Uri(this.host + ":" + this.port + "?clientID=" + this.clientId); CancellationToken cancelTokenConnect = new CancellationToken(); await clientWebsocket.ConnectAsync(url, cancelTokenConnect); connected = true; //TODO: refactor cancelTokenTaskProcessIncomingMsgs = new CancellationToken(); taskProcessIncomingMsgs = Task.Run(async() => { while (clientWebsocket.State == WebSocketState.Open) { try { var bytebuffer = new byte[RECEIVE_BUFFER_SIZE]; ArraySegment <byte> arraySegment = new ArraySegment <byte>(bytebuffer); WebSocketReceiveResult receiveResult = await clientWebsocket.ReceiveAsync(arraySegment, cancelTokenTaskProcessIncomingMsgs); if (receiveResult.EndOfMessage) { if (receiveResult.Count == 4) { string msgString = Encoding.UTF8.GetString(arraySegment.AsMemory().ToArray(), 0, receiveResult.Count); if (msgString == "PING") { // PING message await this.SendBytes(Encoding.UTF8.GetBytes("PONG")); } } else { TopicData topicdata = TopicData.Parser.ParseFrom(arraySegment.Array, 0, receiveResult.Count); if (topicdata.TopicDataRecord != null) { this.InvokeTopicCallbacks(topicdata.TopicDataRecord); } if (topicdata.Error != null) { Debug.LogError(topicdata.Error.ToString()); } } } } catch (Exception ex) { Debug.LogError("WebSocket receive exception: " + ex.ToString()); } try { await FlushRecordsToPublish(); } catch (Exception ex) { Debug.LogError("WebSocket send exception: " + ex.ToString()); } } }); }
internal static ReadOnlyMemory <T> AsReadOnlyMemory <T>(this ArraySegment <T> segment, int start, int length) => segment.AsMemory(start, length);
/// <summary> /// Read bytes from TIFF file source. /// </summary> /// <param name="offset">The offset in the file.</param> /// <param name="buffer">The buffer to hold bytes.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> that fires when the users has requested to stop the IO process.</param> /// <returns>The count of bytes read from file.</returns> public virtual ValueTask <int> ReadAsync(TiffStreamOffset offset, ArraySegment <byte> buffer, CancellationToken cancellationToken = default) => ReadAsync(offset, buffer.AsMemory(), cancellationToken);
private async Task KeepAccept(Socket listenSocket) { while (!_cancellationTokenSource.IsCancellationRequested) { var buffer = default(byte[]); try { var bufferSize = ChannelOptions.MaxPackageLength; buffer = _bufferPool.Rent(bufferSize); var result = await listenSocket .ReceiveFromAsync(new ArraySegment <byte>(buffer, 0, buffer.Length), SocketFlags.None, _acceptRemoteEndPoint) .ConfigureAwait(false); var packageData = new ArraySegment <byte>(buffer, 0, result.ReceivedBytes); var remoteEndPoint = result.RemoteEndPoint as IPEndPoint; var sessionID = _udpSessionIdentifierProvider.GetSessionIdentifier(remoteEndPoint, packageData); var session = await _sessionContainer.GetSessionByIDAsync(sessionID); IVirtualChannel channel = null; if (session != null) { channel = session.Channel as IVirtualChannel; } else { channel = await CreateChannel(_listenSocket, remoteEndPoint, sessionID); if (channel == null) { return; } OnNewClientAccept(channel); } await channel.WritePipeDataAsync(packageData.AsMemory(), _cancellationTokenSource.Token); } catch (Exception e) { if (e is ObjectDisposedException || e is NullReferenceException) { break; } if (e is SocketException se) { var errorCode = se.ErrorCode; //The listen socket was closed if (errorCode == 125 || errorCode == 89 || errorCode == 995 || errorCode == 10004 || errorCode == 10038) { break; } } _logger.LogError(e, $"Listener[{this.ToString()}] failed to receive udp data"); } finally { _bufferPool.Return(buffer); } } _stopTaskCompletionSource.TrySetResult(true); }
/// <summary> /// 创建固定大小的BufferWriter /// </summary> /// <typeparam name="T"></typeparam> /// <param name="arraySegment"></param> /// <returns></returns> public static MemoryBufferWriter <T> CreateWriter <T>(this ArraySegment <T> arraySegment) { return(arraySegment.AsMemory().CreateWriter()); }
public static T Decode <T>(this ITypeTranscoder typeTranscoder, ArraySegment <byte> buffer, int offset, int length, Flags flags, OpCode opcode) { return(typeTranscoder.Decode <T>(buffer.AsMemory(offset, length), flags, opcode)); }
/// <summary> /// Write bytes into TIFF file stream. /// </summary> /// <param name="offset">The offset in the stream.</param> /// <param name="buffer">The buffer to write.</param> public virtual void Write(TiffStreamOffset offset, ArraySegment <byte> buffer) => Write(offset, buffer.AsMemory());