public ReadResult Read(Chunk chunk) { var result = new ReadResult(); var match = Regex.Match(chunk.Text, Paths_Regex); if(match.Success) { // remove extra line feeds var newLines = match.Groups[1].Value.Length > 0 ? "\n" : string.Empty; var replaced = chunk.Text.Replace( match.Groups[0].Value, "{0}Obvious {1}: {2}.".ToFormat( newLines, match.Groups[2].Value, match.Groups[3].Value)); result.Chunk = Chunk.For(replaced); } else { result.Chunk = chunk; } return result; }
public void RenderData(ReadResult result) { if (result.Chunk == null || string.IsNullOrWhiteSpace(result.Chunk.Text) || string.IsNullOrWhiteSpace(result.Chunk.Text.Trim())) return; Log(result.Chunk.Text); }
public ReadResult Parse(Chunk chunk) { var overallResult = new ReadResult(); System.Diagnostics.Debug.WriteLine("Parsing: " + chunk.Text); if(_lastIdx > -1) { var parser = _parsers[_lastIdx]; var result = parser.Read(chunk); chunk = result.Chunk; overallResult.AddTags(result.Tags); if (result.Stop) { if(chunk != null && !string.IsNullOrWhiteSpace(chunk.Text)) { overallResult.Chunk = chunk; } return overallResult; } _lastIdx = -1; } for (var i = 0; i < _parsers.Count; i++) { if (chunk == null) break; var parser = _parsers[i]; var result = parser.Read(chunk); chunk = result.Chunk; overallResult.AddTags(result.Tags); if (result.Stop) { _lastIdx = i; } } if(chunk != null && !string.IsNullOrWhiteSpace(chunk.Text)) { overallResult.Chunk = chunk; } var tags = Transform(overallResult.Tags); overallResult.ClearTags(); overallResult.AddTags(tags); return overallResult; }
public ReadResult ReadFromFile() { long fixedNumber = 1; ReadResult result = new ReadResult(); result.adjacencyMatrix = new bool[fixedNumber, fixedNumber]; result.computers = new Computer[fixedNumber]; result.oses = new Os[fixedNumber]; result.oses[0] = new Os("Test Os"); result.computers[0] = new Computer(result.oses[0]); result.viruses = new Virus[fixedNumber]; var PoisonChances = new Tuple<String, Double>[fixedNumber]; PoisonChances[0] = new Tuple<String, Double>("Test Os", 1); result.viruses[0] = new Virus("Test Virus", PoisonChances); result.computers[0].Virus = result.viruses[0]; return result; }
public ReadResult ReadValues() { var readResult = new ReadResult(); using (var fs = new FileStream(this.config.FullConfigFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (var sr = new StreamReader(fs)) { string line; while ((line = sr.ReadLine()) != null) { this.ProcessLine(line, readResult); } } } return readResult; }
public ReadResult Read(Chunk chunk) { var result = new ReadResult(); if(chunk.Text != null && Regex.IsMatch(chunk.Text, Paths_Regex)) { var replaced = Regex.Replace(chunk.Text, Paths_Regex, "</preset> \nYou also see"); result.Chunk = Chunk.For(replaced); } else { result.Chunk = chunk; } return result; }
public ReadResult LoadPackage(string filename) { ReadResult result = new ReadResult(); string tempDir = Path.Combine(Path.GetTempPath(), "Quest", Guid.NewGuid().ToString()); Directory.CreateDirectory(tempDir); ZipFile zip = ZipFile.Read(filename); zip.ExtractAll(tempDir); result.Folder = tempDir; result.GameFile = Path.Combine(tempDir, "game.aslx"); if (!File.Exists(result.GameFile)) { throw new InvalidDataException("Invalid game file"); } return result; }
private async Task StartSending() { Exception error = null; try { while (true) { ReadResult result = await _application.Input.ReadAsync(); ReadOnlySequence <byte> buffer = result.Buffer; // Get a frame from the application try { if (result.IsCanceled) { break; } if (!buffer.IsEmpty) { try { Log.ReceivedFromApp(_logger, buffer.Length); string data = Convert.ToBase64String(buffer.ToArray()); Log.SendStarted(_logger); await _jsRuntime.InvokeAsync <object>( "BlazorSignalR.WebSocketsTransport.Send", data, DotNetObjectReference.Create(this)); } catch (Exception ex) { if (!_aborted) { Log.ErrorSendingMessage(_logger, ex); } break; } } else if (result.IsCompleted) { break; } } finally { _application.Input.AdvanceTo(buffer.End); } } } catch (Exception ex) { error = ex; } finally { await CloseWebSocketAsync(); _application.Input.Complete(); Log.SendStopped(_logger); } }
protected override bool TryParseRequest(ReadResult result, out bool endConnection) { var examined = result.Buffer.End; var consumed = result.Buffer.End; try { ParseRequest(result.Buffer, out consumed, out examined); } catch (InvalidOperationException) { if (_requestProcessingStatus == RequestProcessingStatus.ParsingHeaders) { throw BadHttpRequestException.GetException(RequestRejectionReason .MalformedRequestInvalidHeaders); } throw; } finally { Input.Advance(consumed, examined); } if (result.IsCompleted) { switch (_requestProcessingStatus) { case RequestProcessingStatus.RequestPending: endConnection = true; return(true); case RequestProcessingStatus.ParsingRequestLine: throw BadHttpRequestException.GetException( RequestRejectionReason.InvalidRequestLine); case RequestProcessingStatus.ParsingHeaders: throw BadHttpRequestException.GetException( RequestRejectionReason.MalformedRequestInvalidHeaders); } } else if (!_keepAlive && _requestProcessingStatus == RequestProcessingStatus.RequestPending) { // Stop the request processing loop if the server is shutting down or there was a keep-alive timeout // and there is no ongoing request. endConnection = true; return(true); } else if (RequestTimedOut) { // In this case, there is an ongoing request but the start line/header parsing has timed out, so send // a 408 response. throw BadHttpRequestException.GetException(RequestRejectionReason.RequestTimeout); } endConnection = false; if (_requestProcessingStatus == RequestProcessingStatus.AppStarted) { EnsureHostHeaderExists(); return(true); } else { return(false); } }
static void FeedDone(IAsyncResult ares) { AsyncResult a = (AsyncResult) ares; ReadResult res = null; try { res = ((ReadDelegate) a.AsyncDelegate).EndInvoke (ares); } catch { res = new ReadResult (UpdateStatus.Error); } if (disable_load) return; Blogger blogger = (Blogger) ares.AsyncState; blogger.Feed = res.Feed; blogger.UpdateFeed (); if (res.Status == UpdateStatus.CachedButError) blogger.Error = true; Settings.Log ("DONE {0}", blogger.RssUrl); lock (all) { loaded++; counters [(int) res.Status]++; if (loaded >= all.Length) wait_handle.Set (); if (next >= all.Length) return; Blogger b = all [next++]; ReadDelegate d = new ReadDelegate (FeedCache.Read); d.BeginInvoke (b.Name, b.RssUrl, feed_done, b); } }
public override bool TryRead(out ReadResult result) => _input.TryRead(out result);
public override bool TryRead(out ReadResult result) { return(_pipeReader.TryRead(out result)); }
public override bool TryRead(out ReadResult result) { ValidateState(); return(_body.TryRead(out result)); }
public async Task <(Message, Stream)> ReceiveAsync(FramingConnection connection, TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); ReadOnlySequence <byte> buffer = ReadOnlySequence <byte> .Empty; for (; ;) { ReadResult readResult = await connection.Input.ReadAsync(); await Task.Yield(); if (readResult.IsCompleted || readResult.Buffer.Length == 0) { if (!readResult.IsCompleted) { connection.Input.AdvanceTo(readResult.Buffer.Start); } //EnsureDecoderAtEof(connection); connection.EOF = true; } if (connection.EOF) { return(null, null); } buffer = readResult.Buffer; bool atEnvelopeStart = DecodeBytes(connection, ref buffer); connection.Input.AdvanceTo(buffer.Start); if (atEnvelopeStart) { break; } if (connection.EOF) { return(null, null); } } // we're ready to read a message Stream connectionStream = new SingletonInputConnectionStream(connection, connection.ServiceDispatcher.Binding); Stream inputStream = new MaxMessageSizeStream(connectionStream, connection.MaxReceivedMessageSize); //using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity(true) : null) //{ // if (DiagnosticUtility.ShouldUseActivity) // { // ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityProcessingMessage, TraceUtility.RetrieveMessageNumber()), ActivityType.ProcessMessage); // } Message message; try { message = await connection.MessageEncoderFactory.Encoder.ReadMessageAsync( inputStream, connection.MaxBufferSize, connection.FramingDecoder.ContentType); } catch (XmlException xmlException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ProtocolException(SR.MessageXmlProtocolError, xmlException)); } //if (DiagnosticUtility.ShouldUseActivity) //{ // TraceUtility.TransferFromTransport(message); //} PrepareMessage(connection, message); return(message, inputStream); //} }
internal async Task ReceiveResponsesAsync() { // bufferSize is the minimum buffer size to rent from ArrayPool<byte>.Shared. We can actually // buffer much more than this value, it is merely the size of the buffer segments which will be used. // When operations larger than this size are encountered, additional segments will be requested from // the pool and retained only until that operation is completed. // // minimumReadSize is the minimum block of data to read into a buffer segment from the stream. If there is // not enough space left in a segment, a new segment will be requested from the pool. This is set to 1500 // to match the default IP MTU on most systems. var reader = PipeReader.Create(_stream, new StreamPipeReaderOptions( bufferSize: 65536, minimumReadSize: 1500)); try { while (true) { ReadResult result = await reader.ReadAsync().ConfigureAwait(false); ReadOnlySequence <byte> buffer = result.Buffer; // Process as many complete operation as we have in the buffer while (TryReadOperation(ref buffer, out IMemoryOwner <byte>?operationResponse)) { try { var opaque = ByteConverter.ToUInt32(operationResponse.Memory.Span.Slice(HeaderOffsets.Opaque)); if (_statesInFlight.TryRemove(opaque, out var state)) { state.Complete(operationResponse); } else { operationResponse.Dispose(); // create orphaned response context // var context = CreateOperationContext(opaque); // send to orphaned response reporter // ClusterOptions.ClientConfiguration.OrphanedResponseLogger.Add(context); } } catch { // Ownership of the buffer was not accepted by state.Complete due to an exception // Make sure we release the buffer operationResponse.Dispose(); throw; } UpdateLastActivity(); } // Tell the reader how much data we've actually consumed, the rest will remain for the next read reader.AdvanceTo(buffer.Start, buffer.End); // Stop reading if there's no more data if (result.IsCompleted) { break; } } HandleDisconnect(new Exception("socket closed.")); } #if NET452 catch (ThreadAbortException) {} #endif catch (ObjectDisposedException) {} catch (SocketException e) { //Dispose has already been thrown by another thread if ((int)e.SocketErrorCode != 10004) { HandleDisconnect(e); } } catch (Exception e) { HandleDisconnect(e); } finally { await reader.CompleteAsync().ConfigureAwait(false); } }
public override bool TryRead(out ReadResult readResult) { ThrowIfReaderCompleted(); return(TryReadInternal(out readResult)); }
private Packet GetPacket(DateTime time, string deviceKey, string packetId) { if (Settings.Instance.FileDeviceKeys.Contains(deviceKey)) { if (deviceKey.IndexOf("labr") >= 0) { Packet p = builder.GetFilePacket(DataSource.Instance.GetLabrDeviceFile(time), "labr"); if (p != null) { p.DeviceKey = deviceKey; p.Id = packetId; return(p); } } else if (deviceKey.IndexOf("hpge") >= 0) { string filePath = DataSource.Instance.GetNewHpGeFile(); if (!string.IsNullOrEmpty(filePath)) { Packet p = builder.GetFilePacket(filePath, "hpge"); if (p != null) { p.DeviceKey = deviceKey; p.Id = packetId; return(p); } } } return(null); } else { if (this.MySqlCmd == null) { this.ConnectToMySQL(); } string errorMsg; DateTime from = time.AddSeconds(-30); ReadResult d = DataSource.GetData(this.MySqlCmd, deviceKey, from, time, this.data, out errorMsg); if (d == ReadResult.ReadDataOK) { if (this.data.Count > 0) { Packet p = builder.GetPacket(deviceKey, this.data, true); p.DeviceKey = deviceKey; p.Id = packetId; return(p); } else { return(null); } } else { // TODO: errorMsg return(null); } } }
internal static bool HasMoreData( this ReadResult readResult) => readResult.IsCanceled == false && readResult.IsCompleted == false;
async Task ReadPipeAsync(PipeReader reader, ClientManager clientManager, RequestReader requestReader) { try { while (true) { ReadResult result = await reader.ReadAsync(); ReadOnlySequence <byte> buffer = result.Buffer; clientManager.MarkActivity(); requestReader.Read(ref buffer); // Tell the PipeReader how much of the buffer we have consumed reader.AdvanceTo(buffer.Start, buffer.End); // Stop reading if there's no more data coming if (result.IsCompleted) { break; } } // Mark the PipeReader as complete reader.Complete(); DisposeClient(clientManager); } catch (SocketException so_ex) { if (ServerMonitor.MonitorActivity) { ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "Error :" + so_ex.ToString()); } DisposeClient(clientManager); } catch (Exception e) { var clientIsDisposed = clientManager.IsDisposed; DisposeClient(clientManager); if (!clientIsDisposed) { AppUtil.LogEvent(e.ToString(), EventLogEntryType.Error); } if (ServerMonitor.MonitorActivity) { ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "Error :" + e.ToString()); } if (SocketServer.Logger.IsErrorLogsEnabled) { SocketServer.Logger.NCacheLog.Error("ConnectionManager.ReceiveCallback", clientManager.ToString() + " Error " + e.ToString()); } try { if (Management.APILogging.APILogManager.APILogManger != null && Management.APILogging.APILogManager.EnableLogging) { APILogItemBuilder log = new APILogItemBuilder(); log.GenerateConnectionManagerLog(clientManager, e.ToString()); } } catch { } } finally { // clientManager.StopCommandExecution(); if (ServerMonitor.MonitorActivity) { ServerMonitor.StopClientActivity(clientManager.ClientID); } } }
public MainViewModel(IPeripheralManager peripheral, IUserDialogs dialogs) { this.dialogs = dialogs; this.ToggleServer = ReactiveCommand.CreateFromTask(async _ => { if (peripheral.IsAdvertising) { this.timer?.Dispose(); this.IsRunning = false; peripheral.ClearServices(); peripheral.StopAdvertising(); this.Write("GATT Server Stopped"); } else { await peripheral.AddService ( ServiceUuid, true, sb => { this.notifications = sb.AddCharacteristic ( NotifyCharacteristicUuid, cb => cb.SetNotification(cs => { var subs = cs.Characteristic.SubscribedCentrals.Count; var @event = cs.IsSubscribing ? "Subscribed" : "Unsubcribed"; this.Write($"Device {cs.Peripheral.Uuid} {@event}"); this.Write($"Charcteristic Subcribers: {subs}"); if (subs == 0) { this.StopTimer(); } else { this.StartTimer(); } }) ); sb.AddCharacteristic ( ReadWriteCharacteristicUuid, cb => cb .SetRead(req => { var value = this.CharacteristicValue ?? "Test"; var bytes = Encoding.UTF8.GetBytes(value); this.Write($"Characteristic Read Received - Sent {value}"); return(ReadResult.Success(bytes)); }) .SetWrite(req => { var write = Encoding.UTF8.GetString(req.Data, 0, req.Data.Length); this.Write($"Characteristic Write Received - {write}"); return(GattState.Success); }) ); } ); await peripheral.StartAdvertising(new AdvertisementData { LocalName = "My GATT" }); this.Write("GATT Server Started with Name: My GATT"); this.IsRunning = true; } }); this.Clear = ReactiveCommand.Create(() => this.Output = String.Empty); }
static void Main(string[] args) { _Token = _TokenSource.Token; Task.Run(() => StartEchoServer(), _Token); _Client = new CavemanTcpClient("127.0.0.1", 9000, false, null, null); _Client.Events.ClientConnected += (s, e) => { Console.WriteLine("[Client] connected"); }; _Client.Events.ClientDisconnected += (s, e) => { Console.WriteLine("[Client] disconnected"); }; while (_RunForever) { Console.Write("Command [? for help]: "); string userInput = Console.ReadLine(); if (String.IsNullOrEmpty(userInput)) { continue; } switch (userInput) { case "?": Console.WriteLine("Available commands:"); Console.WriteLine("q quit"); Console.WriteLine("cls clear the screen"); Console.WriteLine("connect connect to server"); Console.WriteLine("send send clientecho to the server"); Console.WriteLine("read read data from the server"); Console.WriteLine(""); break; case "q": _RunForever = false; break; case "cls": Console.Clear(); break; case "connect": _Client.Connect(5000); break; case "send": _Client.Send("clientecho"); break; case "read": ReadResult rr = _Client.Read(10); if (rr.Status == ReadResultStatus.Success) { Console.WriteLine("[Client] read 10 bytes: " + Encoding.UTF8.GetString(rr.Data)); } else { Console.WriteLine("*** [Client] read status: " + rr.Status.ToString()); } break; } } }
public override async ValueTask <ReadResult> ReadAsyncInternal(CancellationToken cancellationToken = default) { VerifyIsNotReading(); if (_readCompleted) { _isReading = true; return(new ReadResult(_readResult.Buffer, Interlocked.Exchange(ref _userCanceled, 0) == 1, isCompleted: true)); } // The issue is that TryRead can get a canceled read result // which is unknown to StartTimingReadAsync. if (_context.RequestTimedOut) { KestrelBadHttpRequestException.Throw(RequestRejectionReason.RequestBodyTimeout); } await TryStartAsync(); // The while(true) loop is required because the Http1 connection calls CancelPendingRead to unblock // the call to StartTimingReadAsync to check if the request timed out. // However, if the user called CancelPendingRead, we want that to return a canceled ReadResult // We internally track an int for that. while (true) { try { var readAwaitable = _context.Input.ReadAsync(cancellationToken); _isReading = true; _readResult = await StartTimingReadAsync(readAwaitable, cancellationToken); } catch (ConnectionAbortedException ex) { _isReading = false; throw new TaskCanceledException("The request was aborted", ex); } void ResetReadingState() { // Reset the timing read here for the next call to read. StopTimingRead(0); if (!_cannotResetInputPipe) { _isReading = false; _context.Input.AdvanceTo(_readResult.Buffer.Start); } } if (_context.RequestTimedOut) { ResetReadingState(); KestrelBadHttpRequestException.Throw(RequestRejectionReason.RequestBodyTimeout); } if (_readResult.IsCompleted) { ResetReadingState(); ThrowUnexpectedEndOfRequestContent(); } // Ignore the canceled readResult if it wasn't canceled by the user. // Normally we do not return a canceled ReadResult unless CancelPendingRead was called on the request body PipeReader itself, // but if the last call to AdvanceTo examined data it did not consume, we cannot reset the state of the Input pipe. // https://github.com/dotnet/aspnetcore/issues/19476 if (!_readResult.IsCanceled || Interlocked.Exchange(ref _userCanceled, 0) == 1 || _cannotResetInputPipe) { var returnedReadResultLength = CreateReadResultFromConnectionReadResult(); // Don't count bytes belonging to the next request, since read rate timeouts are done on a per-request basis. StopTimingRead(returnedReadResultLength); if (_readResult.IsCompleted) { TryStop(); } break; } ResetReadingState(); } return(_readResult); }
public abstract bool TryReadInternal(out ReadResult readResult);
/// <summary> /// 异步接收数据 /// </summary> /// <param name="session"></param> public void ProcessReadAsync(TSession session) { Task.Run(async() => { try { while (true) { ReadResult result = await session.Reader.ReadAsync(); ReadOnlySequence <byte> buffer = result.Buffer; SequencePosition consumed = buffer.Start; SequencePosition examined = buffer.End; try { if (result.IsCanceled) { break; } var completed = result.IsCompleted; if (buffer.Length > 0) { if (!ReaderBuffer(session, ref buffer, out consumed, out examined)) { completed = true; break; } } if (completed) { break; } } catch (Exception e) { LogHelper.Error($"接收数据出错,{e.Message}"); break; } finally { session.Reader.AdvanceTo(consumed, examined); } } //标记为完成 await session.Reader.CompleteAsync(); } catch (Exception ex) { LogHelper.Error($"接收数据出错,{ex.Message}"); } finally { //接收完毕或者出错后直接关闭连接 Close(session); } }); }
public override bool TryRead(out ReadResult result) { ThrowIfCompleted(); return(TryReadInternal(InternalTokenSource, out result)); }
public override async ValueTask <ReadResult> ReadAsync(CancellationToken cancellationToken = default) { ThrowIfCompleted(); if (_isReading) { throw new InvalidOperationException("Reading is already in progress."); } if (_readCompleted) { _isReading = true; return(_readResult); } TryStart(); // The while(true) loop is required because the Proto1 connection calls CancelPendingRead to unblock // the call to StartTimingReadAsync to check if the request timed out. // However, if the user called CancelPendingRead, we want that to return a canceled ReadResult // We internally track an int for that. while (true) { // The issue is that TryRead can get a canceled read result // which is unknown to StartTimingReadAsync. if (_context.RequestTimedOut) { BadProtoRequestException.Throw(RequestRejectionReason.RequestBodyTimeout); } try { var readAwaitable = _context.Input.ReadAsync(cancellationToken); _isReading = true; _readResult = await StartTimingReadAsync(readAwaitable, cancellationToken); } catch (ConnectionAbortedException ex) { throw new TaskCanceledException("The request was aborted", ex); } if (_context.RequestTimedOut) { BadProtoRequestException.Throw(RequestRejectionReason.RequestBodyTimeout); } // Make sure to handle when this is canceled here. if (_readResult.IsCanceled) { if (Interlocked.Exchange(ref _userCanceled, 0) == 1) { // Ignore the readResult if it wasn't by the user. break; } else { // Reset the timing read here for the next call to read. StopTimingRead(0); continue; } } var readableBuffer = _readResult.Buffer; var readableBufferLength = readableBuffer.Length; StopTimingRead(readableBufferLength); CheckCompletedReadResult(_readResult); if (readableBufferLength > 0) { CreateReadResultFromConnectionReadResult(); break; } } return(_readResult); }
public async Task Connection_Pipe_ReadWrite_Integration(int totalLines) { using SocketsConnectionFactory factory = new SocketsConnectionFactory(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); using SocketTestServer echoServer = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, IPAddress.Loopback); Socket serverSocket = null; echoServer.Accepted += s => serverSocket = s; using Connection connection = await factory.ConnectAsync(echoServer.EndPoint); IDuplexPipe pipe = connection.Pipe; ConcurrentQueue <string> linesSent = new ConcurrentQueue <string>(); Task writerTask = Task.Factory.StartNew(async() => { byte[] endl = Encoding.ASCII.GetBytes("\n"); StringBuilder expectedLine = new StringBuilder(); for (int i = 0; i < totalLines; i++) { int words = i % 10 + 1; for (int j = 0; j < words; j++) { string word = Guid.NewGuid() + " "; Encoding.ASCII.GetBytes(word, pipe.Output); expectedLine.Append(word); } linesSent.Enqueue(expectedLine.ToString()); await pipe.Output.WriteAsync(endl); expectedLine.Clear(); } await pipe.Output.FlushAsync(); // This will also trigger completion on the reader. TODO: Fix // await pipe.Output.CompleteAsync(); }, TaskCreationOptions.LongRunning); // The test server should echo the data sent to it PipeReader reader = pipe.Input; int lineIndex = 0; void ProcessLine(ReadOnlySequence <byte> lineBuffer) { string line = Encoding.ASCII.GetString(lineBuffer); Assert.True(linesSent.TryDequeue(out string expectedLine)); Assert.Equal(expectedLine, line); lineIndex++; // Received everything, shut down the server, so next read will complete: if (lineIndex == totalLines) { serverSocket.Shutdown(SocketShutdown.Both); } } while (true) { try { ReadResult result = await reader.ReadAsync(); ReadOnlySequence <byte> buffer = result.Buffer; SequencePosition? position = null; // Stop reading if there's no more data coming if (result.IsCompleted) { break; } do { // Look for a EOL in the buffer position = buffer.PositionOf((byte)'\n'); if (position != null) { // Process the line ProcessLine(buffer.Slice(0, position.Value)); // Skip the line + the \n character (basically position) buffer = buffer.Slice(buffer.GetPosition(1, position.Value)); } }while (position != null); // Tell the PipeReader how much of the buffer we have consumed reader.AdvanceTo(buffer.Start, buffer.End); } catch (SocketException) { // terminate } } // Mark the PipeReader as complete await reader.CompleteAsync(); await writerTask; // TODO: If this is done in the end of writerTask the socket stops working Assert.Equal(totalLines, lineIndex); }
public override async ValueTask <ReadResult> ReadAsync(CancellationToken cancellationToken = default) { return(this.lastReadResult = await this.inner.ReadAsync(cancellationToken).ConfigureAwait(false)); }
public async Task Serve() { RequestHead reqHead = new RequestHead(); CancellationToken token = _cancellation.Token; try { while (!_cancellation.IsCancellationRequested) { ReadResult result = await _input.ReadAsync(token); if (result.IsCompleted || result.IsCanceled) { return; } ReadOnlySequence <byte> buffer = result.Buffer; if (!_codec.TryReadRequestHead(in buffer, ref reqHead)) { _input.AdvanceTo(buffer.Start, buffer.End); continue; } if (buffer.Length < Protocol.RequestHeadSize + reqHead.PayloadSize) { _input.AdvanceTo(buffer.Start, buffer.End); continue; } ReadOnlySequence <byte> body = buffer.Slice(Protocol.RequestHeadSize, reqHead.PayloadSize); if (!_server.TryGetHandler(reqHead.ServiceID, reqHead.MethodID, out Handler handler)) { _input.AdvanceTo(body.End); _ = SendErrorHead(reqHead.RequestID, ErrorCode.UnknowAPI); continue; } object arg = null; try { arg = handler.ReadArg(_codec, body); } catch (Exception e) { _logger.LogError(e, "ServeLoop: read arguments exception"); _ = SendErrorHead(reqHead.RequestID, ErrorCode.ReadArgError); _input.AdvanceTo(body.End); continue; } _ = ServeOneRequest(handler, reqHead.RequestID, arg); _input.AdvanceTo(body.End); } } catch (OperationCanceledException) { } catch (Exception e) { _logger.LogError(e, "ServeLoop: exception"); } finally { Stop(); } }
static void Main(string[] args) { InitializeClient(); Console.WriteLine("Connecting to tcp://127.0.0.1:8000"); _Client.Connect(10); while (_RunForever) { Console.Write("Command [? for help]: "); string userInput = Console.ReadLine(); if (String.IsNullOrEmpty(userInput)) { continue; } if (userInput.Equals("?")) { Console.WriteLine("-- Available Commands --"); Console.WriteLine(""); Console.WriteLine(" cls Clear the screen"); Console.WriteLine(" q Quit the program"); Console.WriteLine(" send [data] Send data to the server"); Console.WriteLine(" read [count] Read [count] bytes from the server"); Console.WriteLine(" dispose Dispose of the client"); Console.WriteLine(" start Start the client (connected: " + (_Client != null ? _Client.IsConnected.ToString() : "false") + ")"); Console.WriteLine(" stats Retrieve statistics"); Console.WriteLine(""); continue; } if (userInput.Equals("c") || userInput.Equals("cls")) { Console.Clear(); continue; } if (userInput.Equals("q")) { _RunForever = false; break; } if (userInput.StartsWith("send ")) { string[] parts = userInput.Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); string data = parts[1]; _Client.Send(data); } if (userInput.StartsWith("read ")) { string[] parts = userInput.Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); int count = Convert.ToInt32(parts[1]); ReadResult rr = _Client.Read(count); if (rr.Status == ReadResultStatus.Success) { Console.WriteLine("Retrieved " + rr.BytesRead + " bytes: " + Encoding.UTF8.GetString(rr.Data)); } else { Console.WriteLine("Non-success status: " + rr.Status.ToString()); } } if (userInput.Equals("dispose")) { _Client.Dispose(); } if (userInput.Equals("start")) { InitializeClient(); _Client.Connect(10); } if (userInput.Equals("stats")) { Console.WriteLine(_Client.Stats); } } }
public override bool TryReadInternal(out ReadResult readResult) { return(_context.Input.TryRead(out readResult)); }
/// <summary> /// Attempt to perfom a synchronous read operation /// </summary> public override bool TryRead(out ReadResult result) { result = Read(); return(true); }
public override bool TryRead(out ReadResult readResult) { throw new NotImplementedException(); }
public override bool TryRead(out ReadResult result) => throw ThrowInvalidOperationException();
public override bool TryReadInternal(out ReadResult readResult) { VerifyIsNotReading(); if (_readCompleted) { _isReading = true; readResult = new ReadResult(_readResult.Buffer, Interlocked.Exchange(ref _userCanceled, 0) == 1, isCompleted: true); return(true); } if (_context.RequestTimedOut) { KestrelBadHttpRequestException.Throw(RequestRejectionReason.RequestBodyTimeout); } TryStartAsync(); // The while(true) because we don't want to return a canceled ReadResult if the user themselves didn't cancel it. while (true) { if (!_context.Input.TryRead(out _readResult)) { readResult = default; return(false); } if (!_readResult.IsCanceled || Interlocked.Exchange(ref _userCanceled, 0) == 1 || _cannotResetInputPipe) { break; } _context.Input.AdvanceTo(_readResult.Buffer.Start); } if (_readResult.IsCompleted) { if (_cannotResetInputPipe) { _isReading = true; } else { _context.Input.AdvanceTo(_readResult.Buffer.Start); } ThrowUnexpectedEndOfRequestContent(); } var returnedReadResultLength = CreateReadResultFromConnectionReadResult(); // Don't count bytes belonging to the next request, since read rate timeouts are done on a per-request basis. CountBytesRead(returnedReadResultLength); // Only set _isReading if we are returning true. _isReading = true; readResult = _readResult; if (readResult.IsCompleted) { TryStop(); } return(true); }
public ReadResult MoveTo(long recordIndex) { if (recordIndex < 0 || recordIndex > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(recordIndex)); } if (_seekableReader == null && recordIndex < this.CurrentRecordIndex) { throw new InvalidOperationException(Resources.ExceptionMessages.IO_CannotMovePreviousRecordInForwardOnly); } Debug.Assert(_seekableReader == null || _seekableReader.BaseStream.CanSeek); ValidateReader(Validations.IsNotDisposed); if (recordIndex == this.CurrentRecordIndex) { return(ReadResult.Success); } else if (recordIndex < this.CurrentRecordIndex) { _seekableReader.DiscardBufferedData(); _buffer.Clear(); _eof = false; if (this.RecordPositionsCacheEnabled && recordIndex - _recordStreamPositionIndexOffset < _recordStreamPositions.Count) { _seekableReader.BaseStream.Position = Math.Max(_preambleLength, _recordStreamPositions[(int)(recordIndex - _recordStreamPositionIndexOffset)]); this.CurrentRecordIndex = recordIndex - 1; return(Read()); } else { this.StopCachingRecordPositions(true); _seekableReader.BaseStream.Position = _preambleLength; this.CurrentRecordIndex = -1; ReadResult readResult = ReadResult.Success; for (int i = 0; i <= recordIndex; i++) { readResult = this.Read(); if (readResult == ReadResult.EndOfFile) { return(ReadResult.EndOfFile); } } return(readResult); } } else { long offset = recordIndex - this.CurrentRecordIndex; ReadResult readResult = ReadResult.Success; do { readResult = Read(); if (readResult == ReadResult.EndOfFile) { return(ReadResult.EndOfFile); } }while (--offset > 0); return(readResult); } }
private async Task ProcessInternal(PipeReader reader) { ReadResult result = await reader.ReadAsync().ConfigureAwait(false); ReadOnlySequence <byte> buffer = result.Buffer; if (OnReceive == null) { // Tell the PipeReader how much of the buffer we have consumed reader.AdvanceTo(buffer.End); return; } WebSocketMessage <object> stub; try { if (buffer.IsSingleSegment) { stub = JsonSerializer.Deserialize <WebSocketMessage <object> >(buffer.FirstSpan, _jsonOptions); } else { var buf = ArrayPool <byte> .Shared.Rent(Convert.ToInt32(buffer.Length)); try { buffer.CopyTo(buf); stub = JsonSerializer.Deserialize <WebSocketMessage <object> >(buf, _jsonOptions); } finally { ArrayPool <byte> .Shared.Return(buf); } } } catch (JsonException ex) { // Tell the PipeReader how much of the buffer we have consumed reader.AdvanceTo(buffer.End); _logger.LogError(ex, "Error processing web socket message"); return; } // Tell the PipeReader how much of the buffer we have consumed reader.AdvanceTo(buffer.End); _logger.LogDebug("WS {IP} received message: {@Message}", RemoteEndPoint, stub); var info = new WebSocketMessageInfo { MessageType = stub.MessageType, Data = stub.Data?.ToString(), // Data can be null Connection = this }; if (info.MessageType.Equals("KeepAlive", StringComparison.Ordinal)) { await SendKeepAliveResponse(); } else { await OnReceive(info).ConfigureAwait(false); } }
void ProcessLine(string line, ReadResult readResult) { // no, this is not a typo. :) if (line.Contains("custim_timer_source")) { int? val = this.ExtractSettingNumericValue(line); if (val == 0) readResult.CustomTimerSource = LogsLocation.ProfileFolder; else if (val == 1) readResult.CustomTimerSource = LogsLocation.PlayerFolder; } else if (line.Contains("exec_source")) { int? val = this.ExtractSettingNumericValue(line); if (val == 0) readResult.ExecSource = LogsLocation.ProfileFolder; else if (val == 1) readResult.ExecSource = LogsLocation.PlayerFolder; } else if (line.Contains("key_bindings_source")) { int? val = this.ExtractSettingNumericValue(line); if (val == 0) readResult.KeyBindSource = LogsLocation.ProfileFolder; else if (val == 1) readResult.KeyBindSource = LogsLocation.PlayerFolder; } else if (line.Contains("auto_run_source")) { int? val = this.ExtractSettingNumericValue(line); if (val == 0) readResult.AutoRunSource = LogsLocation.ProfileFolder; else if (val == 1) readResult.AutoRunSource = LogsLocation.PlayerFolder; } else if (line.Contains("irc_log_rotation")) { int? val = this.ExtractSettingNumericValue(line); if (val == 0) readResult.IrcLoggingType = LogSaveMode.Never; else if (val == 1) readResult.IrcLoggingType = LogSaveMode.OneFile; else if (val == 2) readResult.IrcLoggingType = LogSaveMode.Monthly; else if (val == 3) readResult.IrcLoggingType = LogSaveMode.Daily; } else if (line.Contains("other_log_rotation")) { int? val = this.ExtractSettingNumericValue(line); if (val == 0) readResult.OtherLoggingType = LogSaveMode.Never; else if (val == 1) readResult.OtherLoggingType = LogSaveMode.OneFile; else if (val == 2) readResult.OtherLoggingType = LogSaveMode.Monthly; else if (val == 3) readResult.OtherLoggingType = LogSaveMode.Daily; } else if (line.Contains("event_log_rotation")) { int? val = this.ExtractSettingNumericValue(line); if (val == 0) readResult.EventLoggingType = LogSaveMode.Never; else if (val == 1) readResult.EventLoggingType = LogSaveMode.OneFile; else if (val == 2) readResult.EventLoggingType = LogSaveMode.Monthly; else if (val == 3) readResult.EventLoggingType = LogSaveMode.Daily; } else if (line.Contains("skillgain_minimum")) { int? val = this.ExtractSettingNumericValue(line); if (val == 0) readResult.SkillGainRate = SkillGainRate.Never; else if (val == 1) readResult.SkillGainRate = SkillGainRate.PerInteger; else if (val == 2) readResult.SkillGainRate = SkillGainRate.Per0D1; else if (val == 3) readResult.SkillGainRate = SkillGainRate.Per0D01; else if (val == 4) readResult.SkillGainRate = SkillGainRate.Per0D001; else if (val == 5) readResult.SkillGainRate = SkillGainRate.Always; } else if (line.Contains("skillgain_no_alignment")) { bool? val = this.ExtractBoolValue(line); if (val == true) readResult.NoSkillMessageOnAlignmentChange = true; else if (val == false) readResult.NoSkillMessageOnAlignmentChange = false; } else if (line.Contains("skillgain_no_favor")) { bool? val = this.ExtractBoolValue(line); if (val == true) readResult.NoSkillMessageOnFavorChange = true; else if (val == false) readResult.NoSkillMessageOnFavorChange = false; } else if (line.Contains("save_skills_on_quit")) { bool? val = this.ExtractBoolValue(line); if (val == true) readResult.SaveSkillsOnQuit = true; else if (val == false) readResult.SaveSkillsOnQuit = false; } else if (line.Contains("setting_timestamps")) { bool? val = this.ExtractBoolValue(line); if (val == true) readResult.TimestampMessages = true; else if (val == false) readResult.TimestampMessages = false; } }
public override bool TryRead(out ReadResult result) { ThrowIfCompleted(); return(_context.Input.TryRead(out result)); }