|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Buffers; |
| 6 | +using System.IO.Pipelines; |
| 7 | +using System.Net; |
| 8 | +using System.Net.Sockets; |
| 9 | +using System.Threading; |
| 10 | +using System.Threading.Tasks; |
| 11 | +using Microsoft.AspNetCore.Connections; |
| 12 | +using Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.Internal; |
| 13 | +using Microsoft.Extensions.Logging; |
| 14 | +using Microsoft.Extensions.Options; |
| 15 | + |
| 16 | +namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.Client |
| 17 | +{ |
| 18 | + class SocketConnectionFactory : IConnectionFactory, IAsyncDisposable |
| 19 | + { |
| 20 | + private readonly SocketTransportOptions _options; |
| 21 | + private readonly MemoryPool<byte> _memoryPool; |
| 22 | + private readonly SocketsTrace _trace; |
| 23 | + |
| 24 | + public SocketConnectionFactory(IOptions<SocketTransportOptions> options, ILoggerFactory loggerFactory) |
| 25 | + { |
| 26 | + if (options == null) |
| 27 | + { |
| 28 | + throw new ArgumentNullException(nameof(options)); |
| 29 | + } |
| 30 | + |
| 31 | + if (loggerFactory == null) |
| 32 | + { |
| 33 | + throw new ArgumentNullException(nameof(loggerFactory)); |
| 34 | + } |
| 35 | + |
| 36 | + _options = options.Value; |
| 37 | + _memoryPool = options.Value.MemoryPoolFactory(); |
| 38 | + var logger = loggerFactory.CreateLogger("Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.Client"); |
| 39 | + _trace = new SocketsTrace(logger); |
| 40 | + } |
| 41 | + |
| 42 | + public async ValueTask<ConnectionContext> ConnectAsync(EndPoint endpoint, CancellationToken cancellationToken = default) |
| 43 | + { |
| 44 | + var ipEndPoint = endpoint as IPEndPoint; |
| 45 | + |
| 46 | + if (ipEndPoint is null) |
| 47 | + { |
| 48 | + throw new NotSupportedException("The SocketConnectionFactory only supports IPEndPoints for now."); |
| 49 | + } |
| 50 | + |
| 51 | + var socket = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) |
| 52 | + { |
| 53 | + NoDelay = _options.NoDelay |
| 54 | + }; |
| 55 | + |
| 56 | + await socket.ConnectAsync(ipEndPoint); |
| 57 | + |
| 58 | + return new SocketConnection(socket, _memoryPool, PipeScheduler.ThreadPool, _trace, _options.MaxReadBufferSize, _options.MaxWriteBufferSize); |
| 59 | + } |
| 60 | + |
| 61 | + public ValueTask DisposeAsync() |
| 62 | + { |
| 63 | + _memoryPool.Dispose(); |
| 64 | + return default; |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments