Skip to content

Commit 809a531

Browse files
committed
refactor: 增加 SetDataPackageAdapter 扩展方法
1 parent 12b687f commit 809a531

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

src/BootstrapBlazor/Extensions/ITcpSocketClientExtensions.cs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,4 +48,30 @@ public static ValueTask<bool> ConnectAsync(this ITcpSocketClient client, string
4848
var endPoint = Utility.ConvertToIpEndPoint(ipString, port);
4949
return client.ConnectAsync(endPoint, token);
5050
}
51+
52+
/// <summary>
53+
/// Configures the specified <see cref="ITcpSocketClient"/> to use the provided <see cref="IDataPackageAdapter"/>
54+
/// for processing received data and sets a callback to handle processed data.
55+
/// </summary>
56+
/// <remarks>This method sets up a two-way data processing pipeline: <list type="bullet"> <item>
57+
/// <description>The <paramref name="client"/> is configured to pass received data to the <paramref name="adapter"/>
58+
/// for processing.</description> </item> <item> <description>The <paramref name="adapter"/> is configured to invoke
59+
/// the provided <paramref name="callback"/> with the processed data.</description> </item> </list> Use this method
60+
/// to integrate a custom data processing adapter with a TCP socket client.</remarks>
61+
/// <param name="client">The <see cref="ITcpSocketClient"/> instance to configure.</param>
62+
/// <param name="adapter">The <see cref="IDataPackageAdapter"/> used to process incoming data.</param>
63+
/// <param name="callback">A callback function invoked with the processed data. The function receives a <see cref="ReadOnlyMemory{T}"/>
64+
/// containing the processed data and returns a <see cref="ValueTask"/>.</param>
65+
public static void SetDataPackageAdapter(this ITcpSocketClient client, IDataPackageAdapter adapter, Func<ReadOnlyMemory<byte>, ValueTask> callback)
66+
{
67+
// 设置 ITcpSocketClient 的回调函数
68+
client.ReceivedCallBack = async buffer =>
69+
{
70+
// 将接收到的数据传递给 DataPackageAdapter 进行数据处理合规数据触发 ReceivedCallBack 回调
71+
await adapter.HandlerAsync(buffer);
72+
};
73+
74+
// 设置 DataPackageAdapter 的回调函数
75+
adapter.ReceivedCallBack = buffer => callback(buffer);
76+
}
5177
}

0 commit comments

Comments
 (0)