Skip to content

Conversation

@ArgoZhang
Copy link
Member

@ArgoZhang ArgoZhang commented Jun 27, 2025

Link issues

fixes #6317

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 timeout parameters and manual receive control to the TCP socket client interface and implementation, integrate consistent cancellation and logging, update data package handlers for cancelable operations, and expand unit tests to cover the new features and edge cases

New Features:

  • Add configurable ConnectTimeout, SendTimeout, and ReceiveTimeout properties to ITcpSocketClient for timeout control
  • Introduce IsAutoReceive flag and a manual ReceiveAsync overload to toggle between automatic and manual data reception
  • Increase the default receive buffer size from 10KB to 64KB in DefaultTcpSocketClient

Enhancements:

  • Implement timeout logic with proper cancellation and logging in ConnectAsync, SendAsync, and receive workflows
  • Refactor DefaultTcpSocketClient to unify manual and automatic receiving via a new ReceiveCoreAsync method
  • Extend IDataPackageHandler and DataPackageHandlerBase to accept CancellationToken parameters for send and receive operations

Documentation:

  • Update ITcpSocketClient and IDataPackageHandler XML documentation to describe new timeout parameters and manual receive behavior

Tests:

  • Add unit tests covering connection timeouts, send and receive timeouts, manual receive behavior, cancellation, and invalid operation scenarios

@bb-auto bb-auto bot added the enhancement New feature or request label Jun 27, 2025
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Jun 27, 2025

Reviewer's Guide

This PR introduces configurable timeout parameters for connect, send, and receive operations in the TCP socket client; refactors the receive logic to support automatic and manual modes; updates data package handlers to propagate cancellation tokens; and expands unit tests to cover timeout and cancellation scenarios.

Sequence diagram for TCP socket connect/send/receive with timeout and cancellation

sequenceDiagram
    participant Client as DefaultTcpSocketClient
    participant Tcp as TcpClient
    participant Handler as IDataPackageHandler
    participant Logger
    actor User

    User->>Client: ConnectAsync(endPoint, token)
    Client->>Tcp: new TcpClient(localEndPoint)
    alt ConnectTimeout > 0
        Client->>Tcp: ConnectAsync(endPoint, connectionToken with timeout)
    else
        Client->>Tcp: ConnectAsync(endPoint, token)
    end
    alt IsAutoReceive
        Client->>Client: AutoReceiveAsync()
    end
    User->>Client: SendAsync(data, token)
    alt SendTimeout > 0
        Client->>Handler: SendAsync(data, sendToken with timeout)
        Client->>Tcp: WriteAsync(data, sendToken with timeout)
    else
        Client->>Handler: SendAsync(data, token)
        Client->>Tcp: WriteAsync(data, token)
    end
    User->>Client: ReceiveAsync(token)
    alt ReceiveTimeout > 0
        Client->>Tcp: ReadAsync(buffer, receiveToken with timeout)
        Client->>Handler: ReceiveAsync(buffer, receiveToken with timeout)
    else
        Client->>Tcp: ReadAsync(buffer, token)
        Client->>Handler: ReceiveAsync(buffer, token)
    end
    Note over Client,Logger: Logs warnings on cancellation or timeout
Loading

Class diagram for updated ITcpSocketClient interface and DefaultTcpSocketClient implementation

classDiagram
    class ITcpSocketClient {
        +int ReceiveBufferSize
        +bool IsConnected
        +bool IsAutoReceive
        +int ConnectTimeout
        +int SendTimeout
        +int ReceiveTimeout
        +IPEndPoint? LocalEndPoint
        +Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallBack
        +ValueTask<bool> ConnectAsync(IPEndPoint, CancellationToken)
        +ValueTask<bool> SendAsync(ReadOnlyMemory<byte>, CancellationToken)
        +ValueTask<Memory<byte>> ReceiveAsync(CancellationToken)
        +void Close()
    }
    class DefaultTcpSocketClient {
        -TcpClient? _client
        -IDataPackageHandler? _dataPackageHandler
        -IPEndPoint? _remoteEndPoint
        -CancellationTokenSource? _receiveCancellationTokenSource
        +IPEndPoint? LocalEndPoint
        +ILogger<DefaultTcpSocketClient>? Logger
        +int ReceiveBufferSize
        +bool IsAutoReceive
        +int ConnectTimeout
        +int SendTimeout
        +int ReceiveTimeout
        +Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallBack
        +ValueTask<bool> ConnectAsync(IPEndPoint, CancellationToken)
        +ValueTask<bool> SendAsync(ReadOnlyMemory<byte>, CancellationToken)
        +ValueTask<Memory<byte>> ReceiveAsync(CancellationToken)
        +void SetDataHandler(IDataPackageHandler)
        +void Close()
        -ValueTask AutoReceiveAsync()
        -ValueTask<int> ReceiveCoreAsync(TcpClient, Memory<byte>, CancellationToken)
    }
    ITcpSocketClient <|.. DefaultTcpSocketClient
Loading

Class diagram for updated IDataPackageHandler and DataPackageHandlerBase

classDiagram
    class IDataPackageHandler {
        +Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallBack
        +ValueTask<ReadOnlyMemory<byte>> SendAsync(ReadOnlyMemory<byte>, CancellationToken)
        +ValueTask ReceiveAsync(ReadOnlyMemory<byte>, CancellationToken)
    }
    class DataPackageHandlerBase {
        +Func<ReadOnlyMemory<byte>, ValueTask>? ReceivedCallBack
        +virtual ValueTask<ReadOnlyMemory<byte>> SendAsync(ReadOnlyMemory<byte>, CancellationToken)
        +virtual ValueTask ReceiveAsync(ReadOnlyMemory<byte>, CancellationToken)
    }
    IDataPackageHandler <|.. DataPackageHandlerBase
    class DelimiterDataPackageHandler {
        +override ValueTask ReceiveAsync(ReadOnlyMemory<byte>, CancellationToken)
    }
    DataPackageHandlerBase <|-- DelimiterDataPackageHandler
    class FixLengthDataPackageHandler {
        +override ValueTask ReceiveAsync(ReadOnlyMemory<byte>, CancellationToken)
    }
    DataPackageHandlerBase <|-- FixLengthDataPackageHandler
Loading

Class diagram for updated method signatures in DataPackageHandlerBase and derived classes

classDiagram
    class DataPackageHandlerBase {
        +virtual ValueTask<ReadOnlyMemory<byte>> SendAsync(ReadOnlyMemory<byte>, CancellationToken)
        +virtual ValueTask ReceiveAsync(ReadOnlyMemory<byte>, CancellationToken)
    }
    class DelimiterDataPackageHandler {
        +override ValueTask ReceiveAsync(ReadOnlyMemory<byte>, CancellationToken)
    }
    class FixLengthDataPackageHandler {
        +override ValueTask ReceiveAsync(ReadOnlyMemory<byte>, CancellationToken)
    }
    DataPackageHandlerBase <|-- DelimiterDataPackageHandler
    DataPackageHandlerBase <|-- FixLengthDataPackageHandler
Loading

File-Level Changes

Change Details Files
Added timeout support for connect, send, and receive operations
  • Introduced ConnectTimeout, SendTimeout, and ReceiveTimeout properties
  • Wrapped ConnectAsync, SendAsync, and receive loops with CancellationTokenSource based on these timeouts
  • Logged separate warnings for cancellations vs. timeouts
DefaultTcpSocketClient.cs
ITcpSocketClient.cs
Refactored receive logic with auto and manual modes
  • Added IsAutoReceive flag to control automatic receiving
  • Split original ReceiveAsync into public manual method and AutoReceiveAsync loop
  • Extracted common code into ReceiveCoreAsync with memory pooling
DefaultTcpSocketClient.cs
Extended data package handlers to accept cancellation tokens
  • Updated IDataPackageHandler and DataPackageHandlerBase signatures to include CancellationToken
  • Propagated token through SendAsync/ReceiveAsync in all handler implementations
IDataPackageHandler.cs
DataPackageHandlerBase.cs
DelimiterDataPackageHandler.cs
FixLengthDataPackageHandler.cs
Expanded and updated unit tests
  • Added tests for connect/send/receive timeouts and cancellations
  • Adjusted existing tests for buffer size default and method renames
TcpSocketFactoryTest.cs

Assessment against linked issues

Issue Objective Addressed Explanation
#6317 Add Timeout parameter to ITcpSocketClient to allow configuring connection, send, and receive timeouts.

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 this to the 9.7.0 milestone Jun 27, 2025
@ArgoZhang ArgoZhang merged commit 45c9979 into main Jun 27, 2025
3 of 4 checks passed
@ArgoZhang ArgoZhang deleted the feat-socket branch June 27, 2025 00:33
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 and they look great!

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `src/BootstrapBlazor/Services/TcpSocket/DefaultTcpSocketClient.cs:35` </location>
<code_context>

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

+    public int ConnectTimeout { get; set; }
+
+    public int SendTimeout { get; set; }
+
+    public int ReceiveTimeout { get; set; }
+
     public void SetDataHandler(IDataPackageHandler handler)
</code_context>

<issue_to_address>
Timeout properties are set as integers without validation.

Please add validation to ensure these timeout properties cannot be set to negative values, as this could cause errors.
</issue_to_address>

### Comment 2
<location> `src/BootstrapBlazor/Services/TcpSocket/DefaultTcpSocketClient.cs:58` </location>
<code_context>
-            // 开始接收数据
-            _ = Task.Run(ReceiveAsync, token);
+            var connectionToken = token;
+            if (ConnectTimeout > 0)
+            {
+                // 设置连接超时时间
+                var connectTokenSource = new CancellationTokenSource(ConnectTimeout);
+                connectionToken = CancellationTokenSource.CreateLinkedTokenSource(token, connectTokenSource.Token).Token;
+            }
+            await _client.ConnectAsync(endPoint, connectionToken);
</code_context>

<issue_to_address>
CancellationTokenSource for timeouts is not disposed.

Not disposing of the CancellationTokenSource may cause resource leaks. Use a using statement or explicitly dispose of it after use.
</issue_to_address>

### Comment 3
<location> `src/BootstrapBlazor/Services/TcpSocket/DefaultTcpSocketClient.cs:171` </location>
<code_context>
-                var buffer = block.Memory;
-                var stream = _client.GetStream();
-                var len = await stream.ReadAsync(buffer, _receiveCancellationTokenSource.Token);
-                if (len == 0)
+                // 设置接收超时时间
+                var receiveTokenSource = new CancellationTokenSource(ReceiveTimeout);
+                receiveToken = CancellationTokenSource.CreateLinkedTokenSource(receiveToken, receiveTokenSource.Token).Token;
+            }
+            len = await stream.ReadAsync(buffer, receiveToken);
+            if (len == 0)
+            {
+                // 远端主机关闭链路
+                Logger.LogInformation("TCP Socket {LocalEndPoint} received 0 data closed by {RemoteEndPoint}", LocalEndPoint, _remoteEndPoint);
+            }
+            else
</code_context>

<issue_to_address>
Zero-length read is logged as information, but connection is not closed.

Consider adding logic to close or clean up the connection when a zero-length read occurs to prevent further operations on a closed socket.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
            if (len == 0)
            {
                // 远端主机关闭链路
                Logger.LogInformation("TCP Socket {LocalEndPoint} received 0 data closed by {RemoteEndPoint}", LocalEndPoint, _remoteEndPoint);
            }
            else
=======
            if (len == 0)
            {
                // 远端主机关闭链路
                Logger.LogInformation("TCP Socket {LocalEndPoint} received 0 data closed by {RemoteEndPoint}", LocalEndPoint, _remoteEndPoint);
                // 关闭连接并清理资源
                try
                {
                    _client?.Close();
                }
                catch (Exception closeEx)
                {
                    Logger.LogWarning(closeEx, "Exception occurred while closing TCP Socket {LocalEndPoint}", LocalEndPoint);
                }
                break; // 退出循环,防止后续操作
            }
            else
>>>>>>> REPLACE

</suggested_fix>

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.

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 Timeout parameter

2 participants