|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the Apache 2.0 License |
| 3 | +// See the LICENSE file in the project root for more information. |
| 4 | +// Maintainer: Argo Zhang([email protected]) Website: https://www.blazor.zone |
| 5 | + |
| 6 | +using Microsoft.Extensions.Logging; |
| 7 | +using System.Buffers; |
| 8 | +using System.Net; |
| 9 | +using System.Net.Sockets; |
| 10 | +using System.Runtime.Versioning; |
| 11 | + |
| 12 | +namespace BootstrapBlazor.Components; |
| 13 | + |
| 14 | +[UnsupportedOSPlatform("browser")] |
| 15 | +class DefaultTcpSocketClient : ITcpSocketClient |
| 16 | +{ |
| 17 | + private TcpClient? _client; |
| 18 | + private IDataPackageHandler? _dataPackageHandler; |
| 19 | + private CancellationTokenSource? _receiveCancellationTokenSource; |
| 20 | + private IPEndPoint? _remoteEndPoint; |
| 21 | + |
| 22 | + public bool IsConnected => _client?.Connected ?? false; |
| 23 | + |
| 24 | + public IPEndPoint LocalEndPoint { get; set; } |
| 25 | + |
| 26 | + [NotNull] |
| 27 | + public ILogger<DefaultTcpSocketClient>? Logger { get; set; } |
| 28 | + |
| 29 | + public int ReceiveBufferSize { get; set; } = 1024 * 10; |
| 30 | + |
| 31 | + public DefaultTcpSocketClient(string host, int port = 0) |
| 32 | + { |
| 33 | + LocalEndPoint = new IPEndPoint(GetIPAddress(host), port); |
| 34 | + } |
| 35 | + |
| 36 | + private static IPAddress GetIPAddress(string host) => host.Equals("localhost", StringComparison.OrdinalIgnoreCase) |
| 37 | + ? IPAddress.Loopback |
| 38 | + : IPAddress.TryParse(host, out var ip) ? ip : IPAddressByHostName; |
| 39 | + |
| 40 | + [ExcludeFromCodeCoverage] |
| 41 | + private static IPAddress IPAddressByHostName => Dns.GetHostAddresses(Dns.GetHostName(), AddressFamily.InterNetwork).FirstOrDefault() ?? IPAddress.Loopback; |
| 42 | + |
| 43 | + public void SetDataHandler(IDataPackageHandler handler) |
| 44 | + { |
| 45 | + _dataPackageHandler = handler; |
| 46 | + } |
| 47 | + |
| 48 | + public Task<bool> ConnectAsync(string host, int port, CancellationToken token = default) |
| 49 | + { |
| 50 | + var endPoint = new IPEndPoint(GetIPAddress(host), port); |
| 51 | + return ConnectAsync(endPoint, token); |
| 52 | + } |
| 53 | + |
| 54 | + public async Task<bool> ConnectAsync(IPEndPoint endPoint, CancellationToken token = default) |
| 55 | + { |
| 56 | + var ret = false; |
| 57 | + try |
| 58 | + { |
| 59 | + // 释放资源 |
| 60 | + Close(); |
| 61 | + |
| 62 | + // 创建新的 TcpClient 实例 |
| 63 | + _client ??= new TcpClient(LocalEndPoint); |
| 64 | + await _client.ConnectAsync(endPoint, token); |
| 65 | + |
| 66 | + // 开始接收数据 |
| 67 | + _ = Task.Run(ReceiveAsync, token); |
| 68 | + |
| 69 | + LocalEndPoint = (IPEndPoint)_client.Client.LocalEndPoint!; |
| 70 | + _remoteEndPoint = endPoint; |
| 71 | + ret = true; |
| 72 | + } |
| 73 | + catch (OperationCanceledException ex) |
| 74 | + { |
| 75 | + Logger.LogWarning(ex, "TCP Socket connect operation was canceled from {LocalEndPoint} to {RemoteEndPoint}", LocalEndPoint, endPoint); |
| 76 | + } |
| 77 | + catch (Exception ex) |
| 78 | + { |
| 79 | + Logger.LogError(ex, "TCP Socket connection failed from {LocalEndPoint} to {RemoteEndPoint}", LocalEndPoint, endPoint); |
| 80 | + } |
| 81 | + return ret; |
| 82 | + } |
| 83 | + |
| 84 | + public async Task<bool> SendAsync(Memory<byte> data, CancellationToken token = default) |
| 85 | + { |
| 86 | + if (_client is not { Connected: true }) |
| 87 | + { |
| 88 | + throw new InvalidOperationException($"TCP Socket is not connected {LocalEndPoint}"); |
| 89 | + } |
| 90 | + |
| 91 | + var ret = false; |
| 92 | + try |
| 93 | + { |
| 94 | + if (_dataPackageHandler != null) |
| 95 | + { |
| 96 | + data = await _dataPackageHandler.SendAsync(data); |
| 97 | + } |
| 98 | + var stream = _client.GetStream(); |
| 99 | + await stream.WriteAsync(data, token); |
| 100 | + ret = true; |
| 101 | + } |
| 102 | + catch (OperationCanceledException ex) |
| 103 | + { |
| 104 | + Logger.LogWarning(ex, "TCP Socket send operation was canceled from {LocalEndPoint} to {RemoteEndPoint}", LocalEndPoint, _remoteEndPoint); |
| 105 | + } |
| 106 | + catch (Exception ex) |
| 107 | + { |
| 108 | + Logger.LogError(ex, "TCP Socket send failed from {LocalEndPoint} to {RemoteEndPoint}", LocalEndPoint, _remoteEndPoint); |
| 109 | + } |
| 110 | + return ret; |
| 111 | + } |
| 112 | + |
| 113 | + private async Task ReceiveAsync() |
| 114 | + { |
| 115 | + _receiveCancellationTokenSource ??= new(); |
| 116 | + while (_receiveCancellationTokenSource is { IsCancellationRequested: false }) |
| 117 | + { |
| 118 | + if (_client is not { Connected: true }) |
| 119 | + { |
| 120 | + throw new InvalidOperationException($"TCP Socket is not connected {LocalEndPoint}"); |
| 121 | + } |
| 122 | + |
| 123 | + try |
| 124 | + { |
| 125 | + using var block = MemoryPool<byte>.Shared.Rent(ReceiveBufferSize); |
| 126 | + var buffer = block.Memory; |
| 127 | + var stream = _client.GetStream(); |
| 128 | + var len = await stream.ReadAsync(buffer, _receiveCancellationTokenSource.Token); |
| 129 | + if (len == 0) |
| 130 | + { |
| 131 | + // 远端主机关闭链路 |
| 132 | + Logger.LogInformation("TCP Socket {LocalEndPoint} received 0 data closed by {RemoteEndPoint}", LocalEndPoint, _remoteEndPoint); |
| 133 | + break; |
| 134 | + } |
| 135 | + else |
| 136 | + { |
| 137 | + buffer = buffer[..len]; |
| 138 | + |
| 139 | + if (_dataPackageHandler != null) |
| 140 | + { |
| 141 | + await _dataPackageHandler.ReceiveAsync(buffer); |
| 142 | + } |
| 143 | + } |
| 144 | + } |
| 145 | + catch (OperationCanceledException ex) |
| 146 | + { |
| 147 | + Logger.LogWarning(ex, "TCP Socket receive operation was canceled from {LocalEndPoint} to {RemoteEndPoint}", LocalEndPoint, _remoteEndPoint); |
| 148 | + } |
| 149 | + catch (Exception ex) |
| 150 | + { |
| 151 | + Logger.LogError(ex, "TCP Socket receive failed from {LocalEndPoint} to {RemoteEndPoint}", LocalEndPoint, _remoteEndPoint); |
| 152 | + } |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + public void Close() |
| 157 | + { |
| 158 | + Dispose(true); |
| 159 | + } |
| 160 | + |
| 161 | + private void Dispose(bool disposing) |
| 162 | + { |
| 163 | + if (disposing) |
| 164 | + { |
| 165 | + _remoteEndPoint = null; |
| 166 | + |
| 167 | + // 取消接收数据的任务 |
| 168 | + if (_receiveCancellationTokenSource is not null) |
| 169 | + { |
| 170 | + _receiveCancellationTokenSource.Cancel(); |
| 171 | + _receiveCancellationTokenSource.Dispose(); |
| 172 | + _receiveCancellationTokenSource = null; |
| 173 | + } |
| 174 | + |
| 175 | + // 释放 TcpClient 资源 |
| 176 | + if (_client != null) |
| 177 | + { |
| 178 | + _client.Close(); |
| 179 | + _client = null; |
| 180 | + } |
| 181 | + } |
| 182 | + } |
| 183 | + |
| 184 | + /// <summary> |
| 185 | + /// <inheritdoc/> |
| 186 | + /// </summary> |
| 187 | + public void Dispose() |
| 188 | + { |
| 189 | + Dispose(true); |
| 190 | + GC.SuppressFinalize(this); |
| 191 | + } |
| 192 | +} |
0 commit comments