Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
@page "/socket/adapter"
@inject IStringLocalizer<Adapters> Localizer

<HeadContent>
<style>
:root {
--bb-row-label-width: 180px;
}
</style>
</HeadContent>

<h3>@Localizer["AdaptersTitle"]</h3>
<h4>@Localizer["AdaptersDescription"]</h4>

Expand Down Expand Up @@ -31,8 +39,22 @@
<li>响应头为 4 字节定长,响应体为 8 个字节定长</li>
<li>响应体为字符串类型数据</li>
</ul>
<p>本示例服务器端模拟了数据分包即响应数据实际是两次写入所以实际接收端是要通过两次接收才能得到一个完整的响应数据包,可通过 <b>数据适配器</b> 来简化接收逻辑。通过切换下方 <b>是否使用数据适配器</b> 控制开关进行测试查看实际数据接收情况</p>
<Pre>private readonly DataPackageAdapter _dataAdapter = new()
{
// 数据适配器内部使用固定长度数据处理器
DataPackageHandler = new FixLengthDataPackageHandler(12)
};

_dataAdapter.ReceivedCallBack += async Data =>
{
// 此处接收到的数据 Data 为完整响应数据
};</Pre>

<div class="row form-inline g-3">
<div class="col-12">
<Switch ShowLabel="true" DisplayText="是否使用数据适配器" @bind-Value="_useDataAdapter"></Switch>
</div>
<div class="col-12 col-sm-6">
<Button Text="连接" Icon="fa-solid fa-play"
OnClick="OnConnectAsync" IsDisabled="@_client.IsConnected"></Button>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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/>
Expand All @@ -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()
Expand All @@ -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 })
Expand All @@ -111,6 +145,8 @@ private void Dispose(bool disposing)
{
if (disposing)
{
_client.ReceivedCallBack -= OnReceivedAsync;

// 释放连接令牌资源
_connectTokenSource.Cancel();
_connectTokenSource.Dispose();
Expand Down
6 changes: 6 additions & 0 deletions src/BootstrapBlazor.Server/Locales/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -7216,5 +7216,11 @@
"ReceivesDescription": "Receive data through Socket and display it",
"NormalTitle": "Basic usage",
"NormalIntro": "After connecting, the timestamp data sent by the server is automatically received through the <code>ReceivedCallBack</code> callback method"
},
"BootstrapBlazor.Server.Components.Samples.Sockets.Adapters": {
"AdaptersTitle": "DataPackageAdapter",
"AdaptersDescription": "Receive data through the data adapter and display",
"NormalTitle": "Basic usage",
"NormalIntro": "After the connection is established, the timestamp data sent by the server is received through the <code>ReceivedCallBack</code> callback method of the <code>DataPackageAdapter</code> data adapter."
}
}
6 changes: 6 additions & 0 deletions src/BootstrapBlazor.Server/Locales/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -7216,5 +7216,11 @@
"ReceivesDescription": "通过 Socket 接收数据并且显示",
"NormalTitle": "基本用法",
"NormalIntro": "连接后通过 <code>ReceivedCallBack</code> 回调方法自动接收服务端发送来的时间戳数据"
},
"BootstrapBlazor.Server.Components.Samples.Sockets.Adapters": {
"AdaptersTitle": "Socket 数据适配器示例",
"AdaptersDescription": "通过数据适配器接收数据并且显示",
"NormalTitle": "基本用法",
"NormalIntro": "连接后通过 <code>DataPackageAdapter</code> 数据适配器的 <code>ReceivedCallBack</code> 回调方法接收服务端发送来的时间戳数据"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Longbow.Tasks.Services;

Expand Down Expand Up @@ -55,11 +56,12 @@ private async Task OnDataHandlerAsync(TcpClient client, CancellationToken stoppi

// 发送响应数据
// 响应头: 4 字节表示响应体长度 [0x32, 0x30, 0x32, 0x35]
// 响应体: 8 字节当前时间戳字符串
var data = new byte[12];
"2025"u8.ToArray().CopyTo(data, 0);
System.Text.Encoding.UTF8.GetBytes(DateTime.Now.ToString("ddHHmmss")).CopyTo(data, 4);
await stream.WriteAsync(data, stoppingToken);
// 响应体: 8 字节当前时间戳字符串
// 此处模拟分包操作故意分 2 次写入数据,导致客户端接收 2 次才能得到完整数据
await stream.WriteAsync("2025"u8.ToArray(), stoppingToken);
// 模拟延时
await Task.Delay(40, stoppingToken);
await stream.WriteAsync(Encoding.UTF8.GetBytes(DateTime.Now.ToString("ddHHmmss")), stoppingToken);
}
catch (OperationCanceledException) { break; }
catch (IOException) { break; }
Expand Down
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
Copy link
Contributor

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:

public class DataPackageAdapter : IDataPackageAdapter
{
    public Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallBack { get; set; }

    private IDataPackageHandler? _handler;
    public IDataPackageHandler? DataPackageHandler
    {
        get => _handler;
        set
        {
            _handler = value;
            if (_handler != null)
            {
                // Wire up once at assignment time
                _handler.ReceivedCallBack = OnHandlerReceivedCallBack;
            }
        }
    }

    public virtual ValueTask ReceiveAsync(ReadOnlyMemory<byte> data, CancellationToken token = default)
    {
        // Single-line forward, no extra async state machine if handler is null
        if (DataPackageHandler is null)
            return default;
        return DataPackageHandler.ReceiveAsync(data, token);
    }

    protected virtual ValueTask OnHandlerReceivedCallBack(ReadOnlyMemory<byte> data)
    {
        // Null-conditional invoke
        return ReceivedCallBack != null
            ? ReceivedCallBack(data)
            : default;
    }
}

Benefits:

  • You assign the handler’s callback exactly once in the setter instead of on every receive.
  • ReceiveAsync becomes a single-line forward, avoiding nested if/await and the extra generated state machine when there’s no handler.
  • The protected callback leverages a null‐conditional return to remove the async/await boilerplate.

{
/// <summary>
/// <inheritdoc/>
/// </summary>
public Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallBack { get; set; }

/// <summary>
/// <inheritdoc/>
/// </summary>
public IDataPackageHandler? DataPackageHandler { get; set; }
Copy link
Contributor

Choose a reason for hiding this comment

The 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);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ public override async ValueTask ReceiveAsync(ReadOnlyMemory<byte> data, Cancella
{
await ReceivedCallBack(_data);
}
continue;
}
}
}
Expand Down
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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,15 @@ public interface IDataPackageHandler
ValueTask<ReadOnlyMemory<byte>> SendAsync(ReadOnlyMemory<byte> data, CancellationToken token = default);

/// <summary>
/// Asynchronously receives data from a source and writes it into the provided memory buffer.
/// Asynchronously receives data and processes it.
/// </summary>
/// <remarks>This method does not guarantee that the entire buffer will be filled. The number of bytes
/// written depends on the availability of data.</remarks>
/// <param name="data">The memory buffer to store the received data. The buffer must be writable and have sufficient capacity.</param>
/// <param name="token">A cancellation token that can be used to cancel the operation. The default value is <see langword="default"/>.</param>
/// <returns>A task that represents the asynchronous operation. The task result contains the number of bytes written to the
/// buffer. Returns 0 if the end of the data stream is reached.</returns>
/// <remarks>The method is designed for asynchronous operations and may be used in scenarios where
/// efficient handling of data streams is required. Ensure that the <paramref name="data"/> parameter contains valid
/// data for processing, and handle potential cancellation using the <paramref name="token"/>.</remarks>
/// <param name="data">The data to be received, represented as a read-only memory block of bytes.</param>
/// <param name="token">A cancellation token that can be used to cancel the operation. Defaults to <see langword="default"/> if not
/// provided.</param>
/// <returns>A <see cref="ValueTask{TResult}"/> containing <see langword="true"/> if the data was successfully received and
/// processed; otherwise, <see langword="false"/>.</returns>
ValueTask ReceiveAsync(ReadOnlyMemory<byte> data, CancellationToken token = default);
}
6 changes: 0 additions & 6 deletions src/BootstrapBlazor/Services/TcpSocket/ITcpSocketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,6 @@ public interface ITcpSocketClient : IAsyncDisposable
/// impact performance.</remarks>
Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallBack { get; set; }

/// <summary>
/// Configures the data handler to process incoming data packages.
/// </summary>
/// <param name="handler">The handler responsible for processing data packages. Cannot be null.</param>
void SetDataHandler(IDataPackageHandler handler);

/// <summary>
/// Establishes an asynchronous connection to the specified endpoint.
/// </summary>
Expand Down
Loading
Loading