77
88namespace BootstrapBlazor . Server . Components . Samples . Tutorials ;
99
10- public partial class SocketApp : ComponentBase
10+ public partial class SocketApp : ComponentBase , IDisposable
1111{
1212 [ Inject , NotNull ]
1313 private ITcpSocketFactory ? TcpSocketFactory { get ; set ; }
@@ -16,7 +16,9 @@ public partial class SocketApp : ComponentBase
1616
1717 private bool _flash = false ;
1818
19- private ITcpSocketClient _client = default ! ;
19+ private ITcpSocketClient _client = null ! ;
20+
21+ private List < ConsoleMessageItem > _items = [ ] ;
2022
2123 /// <summary>
2224 /// <inheritdoc/>
@@ -27,17 +29,74 @@ protected override void OnInitialized()
2729
2830 // 从服务中获取 Socket 实例
2931 _client = TcpSocketFactory . GetOrCreate ( "bb" , key => new IPEndPoint ( IPAddress . Loopback , 0 ) ) ;
30- _flash = _client . IsConnected ;
31- _connectColor = _client . IsConnected ? Color . Success : Color . None ;
32+ _client . ReceivedCallBack += OnReceivedAsync ;
33+ ResetLight ( ) ;
3234 }
3335
3436 private async Task OnConnectAsync ( )
3537 {
3638 if ( _client is { IsConnected : false } )
3739 {
3840 await _client . ConnectAsync ( "127.0.0.1" , 8800 , CancellationToken . None ) ;
39- _flash = _client . IsConnected ;
40- _connectColor = _client . IsConnected ? Color . Success : Color . None ;
41+ ResetLight ( ) ;
42+ }
43+ }
44+
45+ private async Task OnCloseAsync ( )
46+ {
47+ if ( _client is { IsConnected : true } )
48+ {
49+ await _client . CloseAsync ( ) ;
50+ ResetLight ( ) ;
51+ }
52+ }
53+
54+ private void ResetLight ( )
55+ {
56+ _flash = _client . IsConnected ;
57+ _connectColor = _client . IsConnected ? Color . Success : Color . None ;
58+ }
59+
60+ private Task OnClear ( )
61+ {
62+ _items = [ ] ;
63+ return Task . CompletedTask ;
64+ }
65+
66+ private async ValueTask OnReceivedAsync ( ReadOnlyMemory < byte > data )
67+ {
68+ // 将数据显示为十六进制字符串
69+ var payload = System . Text . Encoding . UTF8 . GetString ( data . Span ) ;
70+ _items . Add ( new ConsoleMessageItem
71+ {
72+ Message = $ "接收到来自站点的数据为 { payload } "
73+ } ) ;
74+
75+ // 保持队列中最大数量为 50
76+ if ( _items . Count > 50 )
77+ {
78+ _items . RemoveAt ( 0 ) ;
4179 }
80+ await InvokeAsync ( StateHasChanged ) ;
81+ }
82+
83+ private void Dispose ( bool disposing )
84+ {
85+ if ( disposing )
86+ {
87+ if ( _client is { IsConnected : true } )
88+ {
89+ _client . ReceivedCallBack -= OnReceivedAsync ;
90+ }
91+ }
92+ }
93+
94+ /// <summary>
95+ /// <inheritdoc/>
96+ /// </summary>
97+ public void Dispose ( )
98+ {
99+ Dispose ( true ) ;
100+ GC . SuppressFinalize ( this ) ;
42101 }
43102}
0 commit comments