Skip to content

Commit 3c17b32

Browse files
committed
doc: 更新示例
1 parent b17c4c6 commit 3c17b32

File tree

2 files changed

+64
-29
lines changed

2 files changed

+64
-29
lines changed

src/BootstrapBlazor.Server/Components/Samples/Sockets/Adapters.razor

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,16 @@
2121
<li>点击 <b>断开</b> 按钮调用 <code>CloseAsync</code> 方法断开 Socket 连接</li>
2222
<li>点击 <b>发送</b> 按钮调用 <code>SendAsync</code> 方法发送请求数据</li>
2323
</ul>
24-
<p>本例中已关闭自动接收功能,调用 <code>ReceivedAsync</code> 方法主动接收服务端返回数据</p>
24+
<p class="code-label">通讯协议讲解:</p>
25+
<p>在实际应用开发中,通讯数据协议很多时候是双方约定的。我们假设本示例通讯协议规约为定长格式具体如下:</p>
26+
<ul class="ul-demo">
27+
<li>发送数据包格式为 <code>请求头(Header)+ 请求体(Body)</code> 长度总和为 12 个字节</li>
28+
<li>请求头为 4 字节定长,请求体为 8 个字节定长</li>
29+
<li>请求体为字符串类型数据</li>
30+
<li>返回数据包格式为 <code>响应头(Header)+ 响应体(Body)</code> 长度总和为 12 个字节</li>
31+
<li>响应头为 4 字节定长,响应体为 8 个字节定长</li>
32+
<li>响应体为字符串类型数据</li>
33+
</ul>
2534

2635
<div class="row form-inline g-3">
2736
<div class="col-12 col-sm-6">
@@ -33,7 +42,7 @@
3342
OnClick="OnSendAsync" IsDisabled="@(!_client.IsConnected)"></Button>
3443
</div>
3544
<div class="col-12">
36-
<Console Items="@_items" Height="496" HeaderText="接收数据(间隔 10 秒)"
45+
<Console Items="@_items" Height="496" HeaderText="模拟通讯示例"
3746
ShowAutoScroll="true" OnClear="@OnClear"></Console>
3847
</div>
3948
</div>

src/BootstrapBlazor.Server/Components/Samples/Sockets/Adapters.razor.cs

Lines changed: 53 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
// See the LICENSE file in the project root for more information.
44
// Maintainer: Argo Zhang([email protected]) Website: https://www.blazor.zone
55

6+
using BootstrapBlazor.Server.Components.Components;
67
using System.Net;
8+
using System.Text;
79

810
namespace BootstrapBlazor.Server.Components.Samples.Sockets;
911

@@ -21,8 +23,9 @@ public partial class Adapters : IDisposable
2123

2224
private readonly IPEndPoint _serverEndPoint = new(IPAddress.Loopback, 8900);
2325

24-
private CancellationTokenSource _connectTokenSource = new();
25-
private CancellationTokenSource _sendTokenSource = new();
26+
private readonly CancellationTokenSource _connectTokenSource = new();
27+
private readonly CancellationTokenSource _sendTokenSource = new();
28+
private readonly CancellationTokenSource _receiveTokenSource = new();
2629

2730
/// <summary>
2831
/// <inheritdoc/>
@@ -31,10 +34,12 @@ protected override void OnInitialized()
3134
{
3235
base.OnInitialized();
3336

34-
// 从服务中获取 Socket 实例
37+
// 从服务中获取 ITcpSocketClient 实例
3538
_client = TcpSocketFactory.GetOrCreate("demo-adapter", options =>
3639
{
40+
// 关闭自动接收功能
3741
options.IsAutoReceive = false;
42+
// 设置本地使用的 IP地址与端口
3843
options.LocalEndPoint = new IPEndPoint(IPAddress.Loopback, 0);
3944
});
4045
}
@@ -44,16 +49,41 @@ private async Task OnConnectAsync()
4449
if (_client is { IsConnected: false })
4550
{
4651
await _client.ConnectAsync(_serverEndPoint, _connectTokenSource.Token);
52+
var state = _client.IsConnected ? "成功" : "失败";
53+
_items.Add(new ConsoleMessageItem()
54+
{
55+
Message = $"{DateTime.Now}: 连接 {_client.LocalEndPoint} - {_serverEndPoint} {state}",
56+
Color = _client.IsConnected ? Color.Success : Color.Danger
57+
});
4758
}
4859
}
4960

50-
private async Task SendAsync()
61+
private async Task OnSendAsync()
5162
{
52-
if (_client is { IsConnected: false })
63+
if (_client is { IsConnected: true })
5364
{
5465
// 准备通讯数据
55-
var data = new byte[1024];
56-
await _client.SendAsync(data, _sendTokenSource.Token);
66+
var data = new byte[12];
67+
"2025"u8.CopyTo(data);
68+
Encoding.UTF8.GetBytes(DateTime.Now.ToString("ddHHmmss")).CopyTo(data, 4);
69+
var result = await _client.SendAsync(data, _sendTokenSource.Token);
70+
if (result)
71+
{
72+
// 发送成功
73+
var payload = await _client.ReceiveAsync(_receiveTokenSource.Token);
74+
if (!payload.IsEmpty)
75+
{
76+
// 解析接收到的数据
77+
// 响应头: 4 字节表示响应体长度 [0x32, 0x30, 0x32, 0x35]
78+
// 响应体: 8 字节当前时间戳字符串
79+
data = payload.ToArray();
80+
var body = BitConverter.ToString(data);
81+
_items.Add(new ConsoleMessageItem()
82+
{
83+
Message = $"{DateTime.Now}: 接收到来自 {_serverEndPoint} 数据: {Encoding.UTF8.GetString(data)} HEX: {body}"
84+
});
85+
}
86+
}
5787
}
5888
}
5989

@@ -62,6 +92,12 @@ private async Task OnCloseAsync()
6292
if (_client is { IsConnected: true })
6393
{
6494
await _client.CloseAsync();
95+
var state = _client.IsConnected ? "失败" : "成功";
96+
_items.Add(new ConsoleMessageItem()
97+
{
98+
Message = $"{DateTime.Now}: 关闭 {_client.LocalEndPoint} - {_serverEndPoint} {state}",
99+
Color = _client.IsConnected ? Color.Danger : Color.Success
100+
});
65101
}
66102
}
67103

@@ -71,31 +107,21 @@ private Task OnClear()
71107
return Task.CompletedTask;
72108
}
73109

74-
private async ValueTask OnReceivedAsync(ReadOnlyMemory<byte> data)
75-
{
76-
// 将数据显示为十六进制字符串
77-
var payload = System.Text.Encoding.UTF8.GetString(data.Span);
78-
_items.Add(new ConsoleMessageItem
79-
{
80-
Message = $"接收到来自站点的数据为 {payload}"
81-
});
82-
83-
// 保持队列中最大数量为 50
84-
if (_items.Count > 50)
85-
{
86-
_items.RemoveAt(0);
87-
}
88-
await InvokeAsync(StateHasChanged);
89-
}
90-
91110
private void Dispose(bool disposing)
92111
{
93112
if (disposing)
94113
{
95-
if (_client is { IsConnected: true })
96-
{
114+
// 释放连接令牌资源
115+
_connectTokenSource.Cancel();
116+
_connectTokenSource.Dispose();
97117

98-
}
118+
// 释放发送令牌资源
119+
_sendTokenSource.Cancel();
120+
_sendTokenSource.Dispose();
121+
122+
// 释放接收令牌资源
123+
_receiveTokenSource.Cancel();
124+
_receiveTokenSource.Dispose();
99125
}
100126
}
101127

0 commit comments

Comments
 (0)