|
3 | 3 | // See the LICENSE file in the project root for more information. |
4 | 4 | // Maintainer: Argo Zhang([email protected]) Website: https://www.blazor.zone |
5 | 5 |
|
| 6 | +using System.Net; |
6 | 7 | using System.Text; |
7 | 8 |
|
8 | 9 | namespace BootstrapBlazor.Components; |
@@ -30,4 +31,35 @@ public static ValueTask<bool> SendAsync(this ITcpSocketClient client, string con |
30 | 31 | var buffer = encoding?.GetBytes(content) ?? Encoding.UTF8.GetBytes(content); |
31 | 32 | return client.SendAsync(buffer, token); |
32 | 33 | } |
| 34 | + |
| 35 | + /// <summary> |
| 36 | + /// Establishes an asynchronous connection to the specified host and port. |
| 37 | + /// </summary> |
| 38 | + /// <param name="client">The TCP socket client to which the content will be sent. Cannot be <see langword="null"/>.</param> |
| 39 | + /// <param name="ipString">The hostname or IP address of the server to connect to. Cannot be null or empty.</param> |
| 40 | + /// <param name="port">The port number on the server to connect to. Must be a valid port number between 0 and 65535.</param> |
| 41 | + /// <param name="token">An optional <see cref="CancellationToken"/> to cancel the connection attempt. Defaults to <see |
| 42 | + /// langword="default"/> if not provided.</param> |
| 43 | + /// <returns>A task that represents the asynchronous operation. The task result is <see langword="true"/> if the connection |
| 44 | + /// is successfully established; otherwise, <see langword="false"/>.</returns> |
| 45 | + public static ValueTask<bool> ConnectAsync(this ITcpSocketClient client, string ipString, int port, CancellationToken token = default) |
| 46 | + { |
| 47 | + if (string.IsNullOrEmpty(ipString)) |
| 48 | + { |
| 49 | + throw new ArgumentNullException(nameof(ipString), "IP address cannot be null or empty."); |
| 50 | + } |
| 51 | + |
| 52 | + if (port < 0 || port > 65535) |
| 53 | + { |
| 54 | + throw new ArgumentOutOfRangeException(nameof(port), "Port must be between 0 and 65535."); |
| 55 | + } |
| 56 | + |
| 57 | + if (!IPAddress.TryParse(ipString, out var address)) |
| 58 | + { |
| 59 | + throw new InvalidOperationException($"Invalid IP address format: {ipString}"); |
| 60 | + } |
| 61 | + |
| 62 | + var endPoint = new IPEndPoint(address, port); |
| 63 | + return client.ConnectAsync(endPoint, token); |
| 64 | + } |
33 | 65 | } |
0 commit comments