|
| 1 | +// Copyright (c) Argo Zhang (argo@163.com). All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | +// Website: https://www.blazor.zone or https://argozhang.github.io/ |
| 4 | + |
| 5 | +using Microsoft.Extensions.Logging; |
| 6 | +using System.Buffers; |
| 7 | +using System.Net; |
| 8 | +using System.Net.Sockets; |
| 9 | + |
| 10 | +namespace BootstrapBlazor.Components; |
| 11 | + |
| 12 | +class DefaultTcpSocketClient : ITcpSocketClient |
| 13 | +{ |
| 14 | + private TcpClient? _client; |
| 15 | + |
| 16 | + public bool IsConnected => _client?.Connected ?? false; |
| 17 | + |
| 18 | + public IPEndPoint LocalEndPoint { get; } |
| 19 | + |
| 20 | + public ILogger<DefaultTcpSocketClient>? Logger { get; set; } |
| 21 | + |
| 22 | + public IDataPackageAdapter? DataPackageAdapter { get; set; } |
| 23 | + |
| 24 | + public DefaultTcpSocketClient(string host, int port = 0) |
| 25 | + { |
| 26 | + LocalEndPoint = new IPEndPoint(GetIPAddress(host), port); |
| 27 | + } |
| 28 | + |
| 29 | + private static IPAddress GetIPAddress(string host) => host.Equals("localhost", StringComparison.OrdinalIgnoreCase) |
| 30 | + ? IPAddress.Loopback |
| 31 | + : IPAddress.TryParse(host, out var ip) ? ip : Dns.GetHostAddresses(host).FirstOrDefault() ?? IPAddress.Loopback; |
| 32 | + |
| 33 | + public Task<bool> ConnectAsync(string host, int port, CancellationToken token = default) |
| 34 | + { |
| 35 | + var endPoint = new IPEndPoint(GetIPAddress(host), port); |
| 36 | + return ConnectAsync(endPoint, token); |
| 37 | + } |
| 38 | + |
| 39 | + public async Task<bool> ConnectAsync(IPEndPoint endPoint, CancellationToken token = default) |
| 40 | + { |
| 41 | + var ret = false; |
| 42 | + try |
| 43 | + { |
| 44 | + // 释放资源 |
| 45 | + Close(); |
| 46 | + |
| 47 | + // 创建新的 TouchSocketClient 实例 |
| 48 | + _client ??= new TcpClient(LocalEndPoint); |
| 49 | + await _client.ConnectAsync(endPoint, token); |
| 50 | + ret = true; |
| 51 | + } |
| 52 | + catch (OperationCanceledException ex) |
| 53 | + { |
| 54 | + LogWarning(ex, $"TCP Socket connect operation was canceled to {endPoint}"); |
| 55 | + } |
| 56 | + catch (Exception ex) |
| 57 | + { |
| 58 | + LogError(ex, $"TCP Socket connection failed to {endPoint}"); |
| 59 | + } |
| 60 | + return ret; |
| 61 | + } |
| 62 | + |
| 63 | + public async Task<bool> SendAsync(Memory<byte> data, CancellationToken token = default) |
| 64 | + { |
| 65 | + if (_client is not { Connected: true }) |
| 66 | + { |
| 67 | + throw new InvalidOperationException("TCP Socket is not connected."); |
| 68 | + } |
| 69 | + |
| 70 | + var ret = false; |
| 71 | + try |
| 72 | + { |
| 73 | + var stream = _client.GetStream(); |
| 74 | + await stream.WriteAsync(data, token); |
| 75 | + ret = true; |
| 76 | + } |
| 77 | + catch (OperationCanceledException ex) |
| 78 | + { |
| 79 | + LogWarning(ex, $"TCP Socket send operation was canceled to {_client.Client.RemoteEndPoint}"); |
| 80 | + } |
| 81 | + catch (Exception ex) |
| 82 | + { |
| 83 | + LogError(ex, $"TCP Socket send failed to {_client.Client.RemoteEndPoint}"); |
| 84 | + } |
| 85 | + return ret; |
| 86 | + } |
| 87 | + |
| 88 | + public async Task<Memory<byte>> ReceiveAsync(int bufferSize = 1024 * 10, CancellationToken token = default) |
| 89 | + { |
| 90 | + if (_client is not { Connected: true }) |
| 91 | + { |
| 92 | + throw new InvalidOperationException("TCP Socket is not connected."); |
| 93 | + } |
| 94 | + |
| 95 | + var block = ArrayPool<byte>.Shared.Rent(bufferSize); |
| 96 | + var buffer = new Memory<byte>(block); |
| 97 | + try |
| 98 | + { |
| 99 | + var stream = _client.GetStream(); |
| 100 | + var len = await stream.ReadAsync(buffer, token); |
| 101 | + if (len == 0) |
| 102 | + { |
| 103 | + LogInformation($"TCP Socket received {len} data from {_client.Client.RemoteEndPoint}"); |
| 104 | + } |
| 105 | + else |
| 106 | + { |
| 107 | + buffer = buffer[..len]; |
| 108 | + |
| 109 | + if (DataPackageAdapter != null) |
| 110 | + { |
| 111 | + buffer = await DataPackageAdapter.ReceiveAsync(buffer); |
| 112 | + } |
| 113 | + } |
| 114 | + } |
| 115 | + catch (OperationCanceledException ex) |
| 116 | + { |
| 117 | + LogWarning(ex, $"TCP Socket receive operation was canceled to {_client.Client.RemoteEndPoint}"); |
| 118 | + } |
| 119 | + catch (Exception ex) |
| 120 | + { |
| 121 | + LogError(ex, $"TCP Socket receive failed to {_client.Client.RemoteEndPoint}"); |
| 122 | + } |
| 123 | + finally |
| 124 | + { |
| 125 | + ArrayPool<byte>.Shared.Return(block); |
| 126 | + } |
| 127 | + return buffer; |
| 128 | + } |
| 129 | + |
| 130 | + public void Close() |
| 131 | + { |
| 132 | + Dispose(true); |
| 133 | + } |
| 134 | + |
| 135 | + private void LogInformation(string message) |
| 136 | + { |
| 137 | + Logger?.LogInformation("{message}", message); |
| 138 | + } |
| 139 | + |
| 140 | + private void LogWarning(Exception ex, string message) |
| 141 | + { |
| 142 | + Logger?.LogWarning(ex, "{message}", message); |
| 143 | + } |
| 144 | + |
| 145 | + private void LogError(Exception ex, string message) |
| 146 | + { |
| 147 | + Logger?.LogError(ex, "{message}", message); |
| 148 | + } |
| 149 | + |
| 150 | + private void Dispose(bool disposing) |
| 151 | + { |
| 152 | + if (disposing) |
| 153 | + { |
| 154 | + if (_client != null) |
| 155 | + { |
| 156 | + _client.Close(); |
| 157 | + _client = null; |
| 158 | + } |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + /// <summary> |
| 163 | + /// <inheritdoc/> |
| 164 | + /// </summary> |
| 165 | + public void Dispose() |
| 166 | + { |
| 167 | + Dispose(true); |
| 168 | + GC.SuppressFinalize(this); |
| 169 | + } |
| 170 | +} |
0 commit comments