|
| 1 | +using System.Net.Sockets; |
| 2 | + |
| 3 | +namespace sigtran.net.Layers.SCTP; |
| 4 | + |
| 5 | +/// <summary> |
| 6 | +/// Connects native SCTP client associations. |
| 7 | +/// </summary> |
| 8 | +public sealed class NativeSctpConnector |
| 9 | +{ |
| 10 | + private readonly INativeSctpSocketFactory _socketFactory; |
| 11 | + private readonly NativeSctpConnectionPlanner _planner; |
| 12 | + |
| 13 | + /// <summary>Creates a native SCTP connector.</summary> |
| 14 | + /// <param name="socketFactory">The socket factory.</param> |
| 15 | + /// <param name="planner">The connection planner.</param> |
| 16 | + public NativeSctpConnector( |
| 17 | + INativeSctpSocketFactory? socketFactory = null, |
| 18 | + NativeSctpConnectionPlanner? planner = null) |
| 19 | + { |
| 20 | + _socketFactory = socketFactory ?? new NativeSctpSocketFactory(); |
| 21 | + _planner = planner ?? new NativeSctpConnectionPlanner(); |
| 22 | + } |
| 23 | + |
| 24 | + /// <summary>Connects a native SCTP association.</summary> |
| 25 | + /// <param name="options">The SCTP connection options.</param> |
| 26 | + /// <param name="ct">A cancellation token.</param> |
| 27 | + /// <returns>The connected native SCTP socket adapter.</returns> |
| 28 | + public async Task<NativeSctpSocketAdapter> ConnectAsync(SctpConnectionOptions options, CancellationToken ct = default) |
| 29 | + { |
| 30 | + ArgumentNullException.ThrowIfNull(options); |
| 31 | + |
| 32 | + NativeSctpConnectionPlan plan = await _planner.BuildAsync(options, ct).ConfigureAwait(false); |
| 33 | + Socket socket = _socketFactory.CreateSocket(); |
| 34 | + NativeSctpSocketAdapter? adapter = null; |
| 35 | + |
| 36 | + try |
| 37 | + { |
| 38 | + if (plan.LocalEndpoint is not null) |
| 39 | + { |
| 40 | + socket.Bind(plan.LocalEndpoint); |
| 41 | + } |
| 42 | + |
| 43 | + using CancellationTokenSource timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); |
| 44 | + timeout.CancelAfter(options.ConnectTimeout); |
| 45 | + await socket.ConnectAsync(plan.RemoteEndpoint, timeout.Token).ConfigureAwait(false); |
| 46 | + |
| 47 | + adapter = new NativeSctpSocketAdapter(socket, options, SctpAssociationState.Established); |
| 48 | + return adapter; |
| 49 | + } |
| 50 | + catch |
| 51 | + { |
| 52 | + adapter?.MarkFailed(); |
| 53 | + socket.Dispose(); |
| 54 | + throw; |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments