Skip to content

Conversation

@ArgoZhang
Copy link
Member

@ArgoZhang ArgoZhang commented Jun 20, 2025

Link issues

fixes #6270

Summary By Copilot

Regression?

  • Yes
  • No

Risk

  • High
  • Medium
  • Low

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by Sourcery

Add a string-based SendAsync extension to ITcpSocketClient and introduce an asynchronous ReceivedCallBack mechanism on both the client and data handler layers, update DefaultTcpSocketClient implementation, refresh samples, and extend tests to cover the new functionality.

New Features:

  • Add SendAsync(string) extension method for ITcpSocketClient with optional encoding and cancellation support
  • Introduce ReceivedCallBack property on ITcpSocketClient and DataPackageHandlerBase for registering asynchronous data reception callbacks

Enhancements:

  • Invoke ReceivedCallBack in DefaultTcpSocketClient before handing off to data package handlers
  • Refine sample documentation in SocketFactories.razor to illustrate ReceivedCallBack usage and common package handlers

Documentation:

  • Enhance user-facing documentation to include ReceivedCallBack descriptions and list of built-in data package handlers

Tests:

  • Update TcpSocketFactoryTest to leverage string-based SendAsync and ReceivedCallBack in cancellation and error scenarios
  • Add TouchSocketTest to validate FixLengthDataPackageHandler with split-package handling and ReceivedCallBack integration

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Jun 20, 2025

Reviewer's Guide

This PR introduces a string-based SendAsync extension and a raw data ReceivedCallBack API for ITcpSocketClient and data handlers, updates sample docs to demonstrate the new callback and handler options, and refreshes unit tests (including a new TouchSocketTest suite) to validate these enhancements.

Sequence diagram for ITcpSocketClient.SendAsync(string) extension method

sequenceDiagram
    participant User as actor User
    participant Client as ITcpSocketClient
    participant Extensions as ITcpSocketClientExtensions
    User->>Extensions: SendAsync(client, content, encoding, token)
    Extensions->>Extensions: Convert content to byte[]
    Extensions->>Client: SendAsync(buffer, token)
    Client-->>Extensions: ValueTask<bool>
    Extensions-->>User: ValueTask<bool>
Loading

Sequence diagram for ReceivedCallBack invocation on data reception

sequenceDiagram
    participant Socket as DefaultTcpSocketClient
    participant Callback as ReceivedCallBack
    participant Handler as DataPackageHandlerBase
    Socket->>Socket: ReceiveAsync()
    Socket->>Callback: ReceivedCallBack(buffer)
    Callback-->>Socket: ValueTask
    Socket->>Handler: _dataPackageHandler.ReceiveAsync(buffer)
    Handler-->>Socket: ValueTask
Loading

File-Level Changes

Change Details Files
Add string-based SendAsync extension for ITcpSocketClient
  • Created ITcpSocketClientExtensions with SendAsync(string, Encoding?, CancellationToken) overload
  • Defaulted to UTF-8 when no encoding is supplied
  • Forwarded converted byte buffer to the existing SendAsync API
src/BootstrapBlazor/Extensions/ITcpSocketClientExtensions.cs
Expose ReceivedCallBack property and invoke callbacks on incoming data
  • Added ReceivedCallBack to ITcpSocketClient interface
  • Implemented invocation of ReceivedCallBack in DefaultTcpSocketClient.ReceiveAsync
  • Exposed ReceivedCallBack in DataPackageHandlerBase
src/BootstrapBlazor/Services/TcpSocket/ITcpSocketClient.cs
src/BootstrapBlazor/Services/TcpSocket/DefaultTcpSocketClient.cs
src/BootstrapBlazor/Services/TcpSocket/DataPackage/DataPackageHandlerBase.cs
Refine sample documentation in SocketFactories.razor
  • Added a list item showing how to set ReceivedCallBack
  • Clarified sticky-packet and split-packet descriptions
  • Listed built-in data package handlers
src/BootstrapBlazor.Server/Components/Samples/SocketFactories.razor
Update unit tests to cover new overloads and callbacks
  • Switched to string-based SendAsync calls in TcpSocketFactoryTest
  • Injected and asserted ReceivedCallBack behavior in existing tests
  • Added TouchSocketTest class to simulate servers, test FixLengthDataPackageHandler, and verify callback flow
test/UnitTest/Services/TcpSocketFactoryTest.cs
test/UnitTest/Services/TouchSocketTest.cs

Assessment against linked issues

Issue Objective Addressed Explanation
#6267 Add SendAsync extension method for ITcpSocketClient to send string content.
#6267 Expose ReceivedCallBack property on ITcpSocketClient and DataPackageHandlerBase to handle incoming raw data asynchronously.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@bb-auto bb-auto bot added the enhancement New feature or request label Jun 20, 2025
@bb-auto bb-auto bot added this to the 9.7.0 milestone Jun 20, 2025
sourcery-ai[bot]
sourcery-ai bot previously approved these changes Jun 20, 2025
Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @ArgoZhang - I've reviewed your changes - here's some feedback:

  • The tests use invalid C# array literals like [1, 2, 3]; please replace them with proper new byte[] { 1, 2, 3 } (or equivalent) so they compile.
  • The ReceivedCallBack property name is inconsistent with .NET naming conventions (should be ReceivedCallback); please rename it across interface, implementation, and docs for clarity.
  • The ITcpSocketClientExtensions class lives under the Components namespace, but it extends ITcpSocketClient in Services.TcpSocket; consider moving it to the same namespace or assembly to improve discoverability.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The tests use invalid C# array literals like `[1, 2, 3]`; please replace them with proper `new byte[] { 1, 2, 3 }` (or equivalent) so they compile.
- The `ReceivedCallBack` property name is inconsistent with .NET naming conventions (should be `ReceivedCallback`); please rename it across interface, implementation, and docs for clarity.
- The `ITcpSocketClientExtensions` class lives under the `Components` namespace, but it extends `ITcpSocketClient` in `Services.TcpSocket`; consider moving it to the same namespace or assembly to improve discoverability.

## Individual Comments

### Comment 1
<location> `src/BootstrapBlazor/Services/TcpSocket/DefaultTcpSocketClient.cs:141` </location>
<code_context>
                 {
                     buffer = buffer[..len];

+                    if (ReceivedCallBack != null)
+                    {
+                        await ReceivedCallBack(buffer);
+                    }
+
</code_context>

<issue_to_address>
Consider exception handling for ReceivedCallBack invocation.

If ReceivedCallBack throws, it may break the receive loop or cause side effects. Wrap the invocation in try-catch and handle or log exceptions to improve robustness.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
                    if (ReceivedCallBack != null)
                    {
                        await ReceivedCallBack(buffer);
                    }
=======
                    if (ReceivedCallBack != null)
                    {
                        try
                        {
                            await ReceivedCallBack(buffer);
                        }
                        catch (Exception ex)
                        {
                            // TODO: Replace with your logging framework or error handling as appropriate
                            Console.Error.WriteLine($"Exception in ReceivedCallBack: {ex}");
                        }
                    }
>>>>>>> REPLACE

</suggested_fix>

### Comment 2
<location> `src/BootstrapBlazor/Services/TcpSocket/DefaultTcpSocketClient.cs:31` </location>
<code_context>
+    /// <remarks>The callback function should be designed to handle the received data efficiently and
+    /// asynchronously.  Ensure that the implementation does not block or perform long-running operations, as this may
+    /// impact performance.</remarks>
     public Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallBack { get; set; }

     /// <summary>
</code_context>

<issue_to_address>
Potential naming inconsistency: 'ReceivedCallBack' vs. 'ReceivedCallback'.

Consider renaming to 'ReceivedCallback' to align with standard C# naming conventions.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@ArgoZhang ArgoZhang changed the title feat(ITcpSocketClient): add SendAsync extensions method feat(ITcpSocketClient): add TouchSocket extensions Jun 20, 2025
@ArgoZhang ArgoZhang reopened this Jun 20, 2025
ArgoZhang and others added 2 commits June 20, 2025 13:15
将 `Close` 方法替换为异步的 `CloseAsync` 方法,以支持异步关闭操作并释放资源。`CloseAsync` 方法接受一个消息和一个可选的取消令牌作为参数,并返回一个 `ValueTask<bool>`,指示关闭操作的结果。原有的 `Close` 方法被移除,相关的资源释放逻辑被整合到新的异步方法中。
@codecov
Copy link

codecov bot commented Jun 23, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (0df17f5) to head (1edbe34).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #6268   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          712       712           
  Lines        31397     31397           
  Branches      4437      4437           
=========================================
  Hits         31397     31397           
Flag Coverage Δ
BB 100.00% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ArgoZhang ArgoZhang merged commit d4d76e4 into main Jun 23, 2025
4 checks passed
@ArgoZhang ArgoZhang deleted the feat-TouchSocket branch June 23, 2025 07:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(ITcpSocketClient): add TouchSocket extensions

3 participants