fix(tcp): 会话断开时不再访问已释放的 socket,确保 Disconnected 事件送达
Publish UPM package / publish (push) Successful in 3s
Publish NuGet packages / publish (push) Successful in 1h19m42s

- 服务端/客户端接收循环收尾改用连接时记录的远端地址
- 客户端本地 Stop 导致的读取中断按正常关闭处理
- 观察 Stop 后挂起的 accept 任务异常
- 版本 0.4.4
This commit is contained in:
cneicy committed 2026-11-10 18:36:30 +08:00
1 parent e36917db31
commit 401cecfc14
5 files changed
+62 -14

No files matched your search

@@ -121,9 +121,9 @@ namespace ShrinkNetwork
return;
}
var remote = _client.Client.RemoteEndPoint?.ToString() ?? $"{_host}:{_port}";
var remote = ShrinkTcpServerTransport.TryGetRemoteAddress(_client) ?? $"{_host}:{_port}";
OnEvent?.Invoke(ShrinkNetworkTransportEvent.Connected(_sessionId, remote));
ReceiveLoopAsync(_client, stream, cancellationToken).Forget();
ReceiveLoopAsync(stream, remote, cancellationToken).Forget();
}
catch (Exception ex)
{
@@ -153,7 +153,7 @@ namespace ShrinkNetwork
return sslStream;
}
private async UniTaskVoid ReceiveLoopAsync(TcpClient client, Stream stream, CancellationToken cancellationToken)
private async UniTaskVoid ReceiveLoopAsync(Stream stream, string remote, CancellationToken cancellationToken)
{
try
{
@@ -176,6 +176,14 @@ namespace ShrinkNetwork
catch (OperationCanceledException)
{
}
catch (Exception) when (cancellationToken.IsCancellationRequested)
{
// Stop() cancelled the token and disposed the stream; the pending read fails with
// ObjectDisposedException or IOException. This is a local, intentional shutdown.
}
catch (ObjectDisposedException)
{
}
catch (IOException ex) when (IsExpectedDisconnect(ex))
{
ShrinkNetworkLogger.Warn($"[ShrinkNetwork] TCP receive loop ended: {ex.Message}");
@@ -191,7 +199,8 @@ namespace ShrinkNetwork
}
finally
{
var remote = client.Client.RemoteEndPoint?.ToString() ?? $"{_host}:{_port}";
// Do not read the socket here: Stop() may already have disposed it, and
// Socket.RemoteEndPoint would throw ObjectDisposedException out of this async void.
OnEvent?.Invoke(ShrinkNetworkTransportEvent.Disconnected(_sessionId, remote));
Stop();
}
@@ -202,7 +211,8 @@ namespace ShrinkNetwork
if (string.Equals(ex.Message, "Remote closed.", StringComparison.Ordinal))
return true;
return ex.InnerException is SocketException socketException && IsExpectedDisconnect(socketException);
return ex.InnerException is ObjectDisposedException ||
ex.InnerException is SocketException socketException && IsExpectedDisconnect(socketException);
}
private static bool IsExpectedDisconnect(SocketException ex)