|
| 1 | +using System.Text; |
| 2 | + |
| 3 | +namespace BootstrapBlazor.Server.Components.Samples; |
| 4 | + |
| 5 | +/// <summary> |
| 6 | +/// Term 示例 |
| 7 | +/// </summary> |
| 8 | +public partial class Terms : IDisposable |
| 9 | +{ |
| 10 | + private Term _term = default!; |
| 11 | + private Term _termStream = default!; |
| 12 | + private MemoryStream _ms = new MemoryStream(); |
| 13 | + private CancellationTokenSource? _cancellationTokenSource; |
| 14 | + |
| 15 | + private async Task OnReceivedAsync(byte[] data) |
| 16 | + { |
| 17 | + var str = System.Text.Encoding.UTF8.GetString(data); |
| 18 | + await _term.Write(str.Replace("\r", "\r\n")); |
| 19 | + } |
| 20 | + |
| 21 | + private async Task OnCheck() |
| 22 | + { |
| 23 | + await _term.WriteLine($"Check\r\n{DateTime.Now}"); |
| 24 | + } |
| 25 | + |
| 26 | + private async Task OnTest() |
| 27 | + { |
| 28 | + await _term.WriteLine($"Test\r\n{DateTime.Now}"); |
| 29 | + } |
| 30 | + |
| 31 | + private async Task OnClean() |
| 32 | + { |
| 33 | + await _term.Clear(); |
| 34 | + } |
| 35 | + |
| 36 | + /// <summary> |
| 37 | + /// <inheritdoc/> |
| 38 | + /// </summary> |
| 39 | + /// <param name="firstRender"></param> |
| 40 | + protected override async Task OnAfterRenderAsync(bool firstRender) |
| 41 | + { |
| 42 | + if (firstRender) |
| 43 | + { |
| 44 | + await _termStream.Open(_ms); |
| 45 | + |
| 46 | + _ = Task.Run(async () => |
| 47 | + { |
| 48 | + _cancellationTokenSource ??= new(); |
| 49 | + while (_cancellationTokenSource is { IsCancellationRequested: false }) |
| 50 | + { |
| 51 | + try |
| 52 | + { |
| 53 | + // 模拟流内数据变化 |
| 54 | + _ms.SetLength(0); |
| 55 | + await _ms.WriteAsync(Encoding.UTF8.GetBytes($"{DateTime.Now}\r\n"), _cancellationTokenSource.Token); |
| 56 | + _ms.Seek(0, SeekOrigin.Begin); |
| 57 | + await Task.Delay(2000); |
| 58 | + } |
| 59 | + catch { } |
| 60 | + } |
| 61 | + }); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + private void Dispose(bool disposing) |
| 66 | + { |
| 67 | + if (disposing) |
| 68 | + { |
| 69 | + if (_cancellationTokenSource is { IsCancellationRequested: false }) |
| 70 | + { |
| 71 | + _cancellationTokenSource.Cancel(); |
| 72 | + _cancellationTokenSource.Dispose(); |
| 73 | + _cancellationTokenSource = null; |
| 74 | + } |
| 75 | + |
| 76 | + _ms.Close(); |
| 77 | + _ms.Dispose(); |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + /// <summary> |
| 82 | + /// <inheritdoc/> |
| 83 | + /// </summary> |
| 84 | + public void Dispose() |
| 85 | + { |
| 86 | + Dispose(true); |
| 87 | + GC.SuppressFinalize(this); |
| 88 | + } |
| 89 | +} |
0 commit comments