-
-
Notifications
You must be signed in to change notification settings - Fork 362
doc(IDataPackageAdapter): add DataPackageAdapter sample code #6345
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
b4872f7
refactor: 移除数据处理
ArgoZhang 179bca2
refactor: 增加数据适配器接口
ArgoZhang 03ed5a9
refactor: 重构 ReceiveAsync 方法
ArgoZhang 6ecfb4d
refactor: 更改为实类
ArgoZhang 127b447
feat: 增加模拟分包逻辑
ArgoZhang 7c038c2
doc: 实现接收逻辑
ArgoZhang b777a27
doc: 更新示例
ArgoZhang a8dc603
doc: 更新示例代码
ArgoZhang File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,7 +3,6 @@ | |
| // See the LICENSE file in the project root for more information. | ||
| // Maintainer: Argo Zhang([email protected]) Website: https://www.blazor.zone | ||
|
|
||
| using BootstrapBlazor.Server.Components.Components; | ||
| using System.Net; | ||
| using System.Text; | ||
|
|
||
|
|
@@ -26,6 +25,11 @@ public partial class Adapters : IDisposable | |
| private readonly CancellationTokenSource _connectTokenSource = new(); | ||
| private readonly CancellationTokenSource _sendTokenSource = new(); | ||
| private readonly CancellationTokenSource _receiveTokenSource = new(); | ||
| private readonly DataPackageAdapter _dataAdapter = new() | ||
| { | ||
| DataPackageHandler = new FixLengthDataPackageHandler(12) | ||
| }; | ||
| private bool _useDataAdapter = true; | ||
|
|
||
| /// <summary> | ||
| /// <inheritdoc/> | ||
|
|
@@ -38,10 +42,17 @@ protected override void OnInitialized() | |
| _client = TcpSocketFactory.GetOrCreate("demo-adapter", options => | ||
| { | ||
| // 关闭自动接收功能 | ||
| options.IsAutoReceive = false; | ||
| options.IsAutoReceive = true; | ||
| // 设置本地使用的 IP地址与端口 | ||
| options.LocalEndPoint = new IPEndPoint(IPAddress.Loopback, 0); | ||
| }); | ||
| _client.ReceivedCallBack += OnReceivedAsync; | ||
|
|
||
| _dataAdapter.ReceivedCallBack += async Data => | ||
| { | ||
| // 直接处理接收的数据 | ||
| await UpdateReceiveLog(Data); | ||
| }; | ||
| } | ||
|
|
||
| private async Task OnConnectAsync() | ||
|
|
@@ -67,26 +78,49 @@ private async Task OnSendAsync() | |
| "2025"u8.CopyTo(data); | ||
| Encoding.UTF8.GetBytes(DateTime.Now.ToString("ddHHmmss")).CopyTo(data, 4); | ||
| var result = await _client.SendAsync(data, _sendTokenSource.Token); | ||
| if (result) | ||
| var state = result ? "成功" : "失败"; | ||
|
|
||
| // 记录日志 | ||
| _items.Add(new ConsoleMessageItem() | ||
| { | ||
| // 发送成功 | ||
| var payload = await _client.ReceiveAsync(_receiveTokenSource.Token); | ||
| if (!payload.IsEmpty) | ||
| { | ||
| // 解析接收到的数据 | ||
| // 响应头: 4 字节表示响应体长度 [0x32, 0x30, 0x32, 0x35] | ||
| // 响应体: 8 字节当前时间戳字符串 | ||
| data = payload.ToArray(); | ||
| var body = BitConverter.ToString(data); | ||
| _items.Add(new ConsoleMessageItem() | ||
| { | ||
| Message = $"{DateTime.Now}: 接收到来自 {_serverEndPoint} 数据: {Encoding.UTF8.GetString(data)} HEX: {body}" | ||
| }); | ||
| } | ||
| } | ||
| Message = $"{DateTime.Now}: 发送数据 {_client.LocalEndPoint} - {_serverEndPoint} Data {BitConverter.ToString(data)} {state}" | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| private async ValueTask OnReceivedAsync(ReadOnlyMemory<byte> data) | ||
| { | ||
| if (_useDataAdapter) | ||
| { | ||
| // 使用数据适配器处理接收的数据 | ||
| await _dataAdapter.ReceiveAsync(data, _receiveTokenSource.Token); | ||
| } | ||
| else | ||
| { | ||
| // 直接处理接收的数据 | ||
| await UpdateReceiveLog(data); | ||
| } | ||
| } | ||
|
|
||
| private async Task UpdateReceiveLog(ReadOnlyMemory<byte> data) | ||
| { | ||
| var payload = System.Text.Encoding.UTF8.GetString(data.Span); | ||
| var body = BitConverter.ToString(data.ToArray()); | ||
|
|
||
| _items.Add(new ConsoleMessageItem | ||
| { | ||
| Message = $"{DateTime.Now}: 接收数据 {_client.LocalEndPoint} - {_serverEndPoint} Data {payload} HEX: {body}", | ||
| Color = Color.Success | ||
| }); | ||
|
|
||
| // 保持队列中最大数量为 50 | ||
| if (_items.Count > 50) | ||
| { | ||
| _items.RemoveAt(0); | ||
| } | ||
| await InvokeAsync(StateHasChanged); | ||
| } | ||
|
|
||
| private async Task OnCloseAsync() | ||
| { | ||
| if (_client is { IsConnected: true }) | ||
|
|
@@ -111,6 +145,8 @@ private void Dispose(bool disposing) | |
| { | ||
| if (disposing) | ||
| { | ||
| _client.ReceivedCallBack -= OnReceivedAsync; | ||
|
|
||
| // 释放连接令牌资源 | ||
| _connectTokenSource.Cancel(); | ||
| _connectTokenSource.Dispose(); | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
63 changes: 63 additions & 0 deletions
63
src/BootstrapBlazor/Services/TcpSocket/DataPackage/DataPackageAdapter.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the Apache 2.0 License | ||
| // See the LICENSE file in the project root for more information. | ||
| // Maintainer: Argo Zhang([email protected]) Website: https://www.blazor.zone | ||
|
|
||
| namespace BootstrapBlazor.Components; | ||
|
|
||
| /// <summary> | ||
| /// Provides a base implementation for adapting data packages between different systems or formats. | ||
| /// </summary> | ||
| /// <remarks>This abstract class serves as a foundation for implementing custom data package adapters. It defines | ||
| /// common methods for sending, receiving, and handling data packages, as well as a property for accessing the | ||
| /// associated data package handler. Derived classes should override the virtual methods to provide specific behavior | ||
| /// for handling data packages.</remarks> | ||
| public class DataPackageAdapter : IDataPackageAdapter | ||
| { | ||
| /// <summary> | ||
| /// <inheritdoc/> | ||
| /// </summary> | ||
| public Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallBack { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// <inheritdoc/> | ||
| /// </summary> | ||
| public IDataPackageHandler? DataPackageHandler { get; set; } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nitpick: DataPackageHandler is settable on the adapter, but only gettable on the interface. This inconsistency may confuse consumers who expect to set DataPackageHandler via the interface. |
||
|
|
||
| /// <summary> | ||
| /// <inheritdoc/> | ||
| /// </summary> | ||
| /// <param name="data"></param> | ||
| /// <param name="token"></param> | ||
| /// <returns></returns> | ||
| public virtual async ValueTask ReceiveAsync(ReadOnlyMemory<byte> data, CancellationToken token = default) | ||
| { | ||
| if (DataPackageHandler != null) | ||
| { | ||
| if (DataPackageHandler.ReceivedCallBack == null) | ||
| { | ||
| DataPackageHandler.ReceivedCallBack = OnHandlerReceivedCallBack; | ||
| } | ||
|
|
||
| // 如果存在数据处理器则调用其处理方法 | ||
| await DataPackageHandler.ReceiveAsync(data, token); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Handles incoming data by invoking a callback method, if one is defined. | ||
| /// </summary> | ||
| /// <remarks>This method is designed to be overridden in derived classes to provide custom handling of | ||
| /// incoming data. If a callback method is assigned, it will be invoked asynchronously with the provided | ||
| /// data.</remarks> | ||
| /// <param name="data">The incoming data to be processed, represented as a read-only memory block of bytes.</param> | ||
| /// <returns></returns> | ||
| protected virtual async ValueTask OnHandlerReceivedCallBack(ReadOnlyMemory<byte> data) | ||
| { | ||
| if (ReceivedCallBack != null) | ||
| { | ||
| // 调用接收回调方法处理数据 | ||
| await ReceivedCallBack(data); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
42 changes: 42 additions & 0 deletions
42
src/BootstrapBlazor/Services/TcpSocket/DataPackage/IDataPackageAdapter.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the Apache 2.0 License | ||
| // See the LICENSE file in the project root for more information. | ||
| // Maintainer: Argo Zhang([email protected]) Website: https://www.blazor.zone | ||
|
|
||
| namespace BootstrapBlazor.Components; | ||
|
|
||
| /// <summary> | ||
| /// Defines an adapter for handling and transmitting data packages to a target destination. | ||
| /// </summary> | ||
| /// <remarks>This interface provides methods for sending data asynchronously and configuring a data handler. | ||
| /// Implementations of this interface are responsible for managing the interaction between the caller and the underlying | ||
| /// data transmission mechanism.</remarks> | ||
| public interface IDataPackageAdapter | ||
| { | ||
| /// <summary> | ||
| /// Gets or sets the callback function to be invoked when data is received. | ||
| /// </summary> | ||
| /// <remarks>The callback function is expected to handle the received data asynchronously. Ensure that the | ||
| /// implementation of the callback does not block the calling thread and completes promptly to avoid performance | ||
| /// issues.</remarks> | ||
| Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallBack { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Gets the handler responsible for processing data packages. | ||
| /// </summary> | ||
| IDataPackageHandler? DataPackageHandler { get; } | ||
|
|
||
| /// <summary> | ||
| /// Asynchronously receives data from a source and processes it. | ||
| /// </summary> | ||
| /// <remarks>This method does not return any result directly. It is intended for scenarios where data is received | ||
| /// and processed asynchronously. Ensure that the <paramref name="data"/> parameter contains valid data before calling | ||
| /// this method.</remarks> | ||
| /// <param name="data">A read-only memory region containing the data to be received. The caller must ensure the memory is valid and | ||
| /// populated.</param> | ||
| /// <param name="token">An optional cancellation token that can be used to cancel the operation. Defaults to <see langword="default"/> if | ||
| /// not provided.</param> | ||
| /// <returns>A <see cref="ValueTask"/> representing the asynchronous operation. The task completes when the data has been | ||
| /// successfully received and processed.</returns> | ||
| ValueTask ReceiveAsync(ReadOnlyMemory<byte> data, CancellationToken token = default); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
issue (complexity): Consider simplifying callback assignment and method logic by wiring the handler callback in the setter and streamlining ReceiveAsync and the protected callback method.
Here’s one way to keep exactly the same behavior but collapse the two-step “hook up callback on first receive” into a single, simpler setter and eliminate the nested null‐checks in
ReceiveAsync:Benefits:
ReceiveAsyncbecomes a single-line forward, avoiding nestedif/awaitand the extra generated state machine when there’s no handler.async/awaitboilerplate.