SocketTransportFactory

We found 10 examples in language CSharp for this search. You will see 37 fragments of code.

        public SocketsServerBuilder Listen(EndPoint endPoint, Action<IConnectionBuilder> configure)
        {
            _bindings.Add((endPoint, 0, configure));
            return this;
        }

        public SocketsServerBuilder Listen(IPAddress address, int port, Action<IConnectionBuilder> configure)
        {
            return Listen(new IPEndPoint(address, port), configure);
        }

        public SocketsServerBuilder ListenAnyIP(int port, Action<IConnectionBuilder> configure)
        {
            return Listen(IPAddress.Any, port, configure);
        }

        public SocketsServerBuilder ListenLocalhost(int port, Action<IConnectionBuilder> configure)
        {
            _bindings.Add((null, port, configure));
            return this;
        }

        public SocketsServerBuilder ListenUnixSocket(string socketPath, Action<IConnectionBuilder> configure)
        {
            return Listen(new UnixDomainSocketEndPoint(socketPath), configure);
        }

        internal void Apply(ServerBuilder builder)
        {
            var socketTransportFactory = new SocketTransportFactory(Microsoft.Extensions.Options.Options.Create(Options), builder.ApplicationServices.GetLoggerFactory());

            foreach (var binding in _bindings)
            {
                if (binding.EndPoint == null)
                {
                    var connectionBuilder = new ConnectionBuilder(builder.ApplicationServices);
                    binding.Application(connectionBuilder);
                    builder.Bindings.Add(new LocalHostBinding(binding.Port, connectionBuilder.Build(), socketTransportFactory));
                }
                else
                {

                    builder.Listen(binding.EndPoint, socketTransportFactory, binding.Application);
                }
            }
        }

        [Fact]
        public async Task ThrowsNotSupportedExceptionWhenBindingToFileHandleEndPoint()
        {
            var socketTransportFactory = new SocketTransportFactory(Options.Create(new SocketTransportOptions()), Mock.Of<ILoggerFactory>());
            await Assert.ThrowsAsync<NotSupportedException>(async () => await socketTransportFactory.BindAsync(new FileHandleEndPoint(0, FileHandleType.Auto)));
        }

        [Fact]
        public async Task ThrowsNotImplementedExceptionWhenBindingToUriEndPoint()
        {
            var socketTransportFactory = new SocketTransportFactory(Options.Create(new SocketTransportOptions()), Mock.Of<ILoggerFactory>());
            await Assert.ThrowsAsync<NotImplementedException>(async () => await socketTransportFactory.BindAsync(new UriEndPoint(new Uri("http://127.0.0.1:5554"))));
        }


        public SocketsServerBuilder Listen(EndPoint endPoint, Action<IConnectionBuilder> configure)
        {
            _bindings.Add((endPoint, 0, configure));
            return this;
        }

        public SocketsServerBuilder Listen(IPAddress address, int port, Action<IConnectionBuilder> configure)
        {
            return Listen(new IPEndPoint(address, port), configure);
        }

        public SocketsServerBuilder ListenAnyIP(int port, Action<IConnectionBuilder> configure)
        {
            return Listen(IPAddress.Any, port, configure);
        }

        public SocketsServerBuilder ListenLocalhost(int port, Action<IConnectionBuilder> configure)
        {
            _bindings.Add((null, port, configure));
            return this;
        }

        public SocketsServerBuilder ListenUnixSocket(string socketPath, Action<IConnectionBuilder> configure)
        {
            return Listen(new UnixDomainSocketEndPoint(socketPath), configure);
        }

        internal void Apply(ServerBuilder builder)
        {
            var socketTransportFactory = new SocketTransportFactory(Microsoft.Extensions.Options.Options.Create(Options), builder.ApplicationServices.GetLoggerFactory());

            foreach (var binding in _bindings)
            {
                if (binding.EndPoint == null)
                {
                    var connectionBuilder = new ConnectionBuilder(builder.ApplicationServices);
                    binding.Application(connectionBuilder);
                    builder.Bindings.Add(new LocalHostBinding(binding.Port, connectionBuilder.Build(), socketTransportFactory));
                }
                else
                {

                    builder.Listen(binding.EndPoint, socketTransportFactory, binding.Application);
                }
            }
        }

                public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseSockets(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, System.Action<Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketTransportOptions> configureOptions) => throw null;
                public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseSockets(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder) => throw null;
                            public System.Threading.Tasks.ValueTask<Microsoft.AspNetCore.Connections.IConnectionListener> BindAsync(System.Net.EndPoint endpoint, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) => throw null;

        [Fact]
        public async Task ThrowsNotSupportedExceptionWhenBindingToFileHandleEndPoint()
        {
            var socketTransportFactory = new SocketTransportFactory(Options.Create(new SocketTransportOptions()), Mock.Of<ILoggerFactory>());
            await Assert.ThrowsAsync<NotSupportedException>(async () => await socketTransportFactory.BindAsync(new FileHandleEndPoint(0, FileHandleType.Auto)));
        }

        [Fact]
        public async Task ThrowsNotImplementedExceptionWhenBindingToUriEndPoint()
        {
            var socketTransportFactory = new SocketTransportFactory(Options.Create(new SocketTransportOptions()), Mock.Of<ILoggerFactory>());
            await Assert.ThrowsAsync<NotImplementedException>(async () => await socketTransportFactory.BindAsync(new UriEndPoint(new Uri("http://127.0.0.1:5554"))));
        }



        public async Task StartAsync()
        {
            if (this.runningTaskCompletionSource != null)
            {
                throw new InvalidOperationException("Service has already been started.");
            }

            this.runningTaskCompletionSource = new TaskCompletionSource();

            this.logger.LogInformation("Listening on http://0.0.0.0:{Port}, press Ctrl-C to stop ...", config.Port);
            foreach (string route in this.router.Routes)
            {
                this.logger.LogInformation("Registered route: /{Route}/", route);
            }

            // Set up Ctrl-Break and Ctrl-C handler.
            Console.CancelKeyPress += this.HandleControlC;

            // Start the service.
            SydneyHttpApplication httpApplication =
                new SydneyHttpApplication(
                    this.router,
                    this.config.ReturnExceptionMessagesInResponse,
                    this.loggerFactory);
            await this.server.StartAsync(httpApplication, CancellationToken.None);

            // Await a TaskCompletionSource to make this function not return until the service is stopped.
            await this.runningTaskCompletionSource.Task;
        }

        public async Task StopAsync()
        {
            if (this.runningTaskCompletionSource == null)
            {
                throw new InvalidOperationException("Cannot stop the service when it has not been started.");
            }

            this.runningTaskCompletionSource.SetResult();
            this.runningTaskCompletionSource = null;

            this.logger.LogInformation("Stopping service ...");

            await this.server.StopAsync(CancellationToken.None);

            // Remove Ctrl-Break and Ctrl-C handler.
            Console.CancelKeyPress -= this.HandleControlC;
        }

        public void AddRoute(string route, RestHandlerBase handler)
        {
            if (route == null)
            {
                throw new ArgumentNullException(nameof(route));
            }

            if (handler == null)
            {
                throw new ArgumentNullException(nameof(handler));
            }

            if (this.runningTaskCompletionSource != null)
            {
                throw new InvalidOperationException("Cannot add a route after the service has been started.");
            }

            // Trim leading and trailing slashes from the route.
            this.router.AddRoute(route.Trim('/'), handler);
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.server?.Dispose();
            }
        }

        private async void HandleControlC(object? sender, ConsoleCancelEventArgs e)
        {
            // Stop the Ctrl+C or Ctrl+Break command from terminating the server immediately.
            e.Cancel = true;

            await this.StopAsync();
        }


        public ValueTask<IConnectionListener> BindAsync(EndPoint endpoint,
            CancellationToken cancellationToken = new())
        {
            return endpoint switch
            {
                UdpEndpoint udp => CreateUdpListener(udp),
                _ => _socketTransportFactory.BindAsync(endpoint, cancellationToken)
            };
        }

        private ValueTask<IConnectionListener> CreateUdpListener(UdpEndpoint udp)
        {
            var transport = new UdpConnectionListener(udp);
            transport.Bind();
            return new ValueTask<IConnectionListener>(transport);
        }


        public Task StartAsync()
        {
            this.Running = true;

            this.logger.LogInformation("Starting service, press Ctrl-C to stop ...");
            foreach (string prefix in this.Prefixes)
            {
                // TODO: No longer sure this is the best way to do this now that they're
                // not needed for the listener.
                this.logger.LogInformation($"Listening on prefix: {prefix}");
            }

            // Set up Ctrl-Break and Ctrl-C handler.
            Console.CancelKeyPress += this.HandleControlC;

            return this.server.StartAsync(this, CancellationToken.None);
        }

        public async Task StopAsync()
        {
            if (!this.Running)
            {
                throw new InvalidOperationException("Cannot stop the service when it has not been started.");
            }

            this.Running = false;
            
            this.logger.LogInformation("Stopping service ...");

            await this.server.StopAsync(CancellationToken.None);

            // Remove Ctrl-Break and Ctrl-C handler.
            Console.CancelKeyPress -= this.HandleControlC;
        }

        public void AddRoute(string route, RestHandlerBase handler)
        {
            if (this.Running)
            {
                throw new InvalidOperationException("Cannot add a route after the service has been started.");
            }

            // Trim leading and trailing slashes from the route.
            route = route.Trim('/');

            // Keep track of prefixes to register as routes are added.
            string prefixPath = this.router.AddRoute(route, handler);
            string prefix = string.Format(this.fullPrefixFormat, prefixPath);
            this.Prefixes.Add(prefix);
        }

        public async Task ProcessRequestAsync(DefaultHttpContext context)
        {
            // Try to match the incoming URL to a handler.
            if (!this.router.TryMatchPath(context.Request.Path.Value, out RouteMatch match))
            {
                this.logger.LogWarning($"No matching handler found for incoming request url: {context.Request.Url}.");

                // If we couldn't, return a 404.
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                context.Response.Close();

                return;
            }
        }

        public DefaultHttpContext CreateContext(IFeatureCollection contextFeatures)
        {
            return new DefaultHttpContext(contextFeatures);
        }

        public void DisposeContext(DefaultHttpContext context, Exception? exception)
        {
            if (exception != null)
            {
                this.logger.LogError(
                    exception,
                    $"Unexpected exception handling context, exception: {exception}");
            }
        }


        /// <summary>
        /// Starts listening for new Websocket stream connections
        /// </summary>
        /// <param name="endpoint">The endpoint to listen to</param>
        /// <param name="connectionAdded">A connection delegate that is called when a new client is connected</param>
        /// <param name="bufferSize">Buffer sized used for receiving</param>
        /// <param name="defaultPage">Default response to clients like browsers</param>
        /// <returns></returns>
        public Task StartAsync(IPEndPoint endpoint, Func<WsStream, Task> connectionAdded, int bufferSize = Config.InternalBufferSize, string defaultPage = Config.Version)
        {
            if (IsListening) throw new InvalidOperationException("WsServer is already running!");
            _stopSource = new CancellationTokenSource();
            IsListening = true;
            // setup kestrel parameters
            var logger = new NullLoggerFactory();
            var kestrelOptions = new KestrelServerOptions();
            #if NETSTANDARD2_0
            var lifetime = new ApplicationLifetime();
            var socketTransportFactory = new SocketTransportFactory(Options.Create(new SocketTransportOptions()), lifetime, logger);
            #else
            var socketTransportFactory = new SocketTransportFactory(Options.Create(new SocketTransportOptions()), logger);
            #endif
            // start kestrel
            _server = new KestrelServer(Options.Create(kestrelOptions), socketTransportFactory, logger);
            _server.Options.Listen(endpoint);
            return _server
                .StartAsync(new KestrelRequestHandler(connectionAdded, bufferSize, _stopSource.Token, defaultPage),
                    CancellationToken.None).ContinueWith(
                    x =>
                    {
                        var addr = _server.Features.Get<IServerAddressesFeature>();
                        ListeningAddresses = addr.Addresses.ToArray();
                    });
        }

        /// <summary>
        /// Shuts down the server
        /// </summary>
        public async Task StopAsync()
        {
            if (IsListening)
            {
                IsListening = false;
                _stopSource.Cancel();
                var cts = new CancellationTokenSource(500);
                await _server.StopAsync(cts.Token);
                _stopSource.Dispose();
                _server.Dispose();
            }
        }
        /// <summary>
        /// Stops the server, and disposes any resources
        /// </summary>
        public void Dispose()
        {
            StopAsync().GetAwaiter().GetResult();
        }


		public async ValueTask<TransportFactoryBindResult> TryBindAsync(EndPoint endpoint, CancellationToken cancellationToken = default)
		{
			if (endpoint is FileHandleEndPoint ||
				endpoint is UnixDomainSocketEndPoint ||
				(endpoint is IPEndPoint ipEndPoint &&
				ipEndPoint.Port != 0)) //  a port of 0 indicates an extension endpoint masquerading as an IPEndPoint to avoid Kestrel throwing exceptions
			{
				return new TransportFactoryBindResult(
					true, endpoint, await _factory.BindAsync(endpoint, cancellationToken)
					);
			}

			return new TransportFactoryBindResult(endpoint);
		}

Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketTransportFactory : ITransportFactory

Constructors :

public SocketTransportFactory(IOptions<SocketTransportOptions> options = , IApplicationLifetime applicationLifetime = , ILoggerFactory loggerFactory = )

Methods :

public ITransport Create(IEndPointInformation endPointInformation = , IConnectionDispatcher dispatcher = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()

Other methods

Other methods