Beispiel #1
0
        public static KestrelHttpServer StartNew(int port, HttpScheme scheme, IHttpHandler handler,
                                                 KestrelServerSettings serverSettings, ILog log)
        {
            var server = new KestrelHttpServer(handler, log, serverSettings);

            server.Start(port, scheme);
            return(server);
        }
Beispiel #2
0
 public void InitServicePoint(string url, HttpScheme scheme)
 {
     _domain = new ServicePoint()
     {
         ServiceUrl = url,
         Scheme     = scheme,
     };
 }
Beispiel #3
0
 public static string?SchemeToString(HttpScheme scheme)
 {
     return(scheme switch
     {
         HttpScheme.Http => HttpUriScheme,
         HttpScheme.Https => HttpsUriScheme,
         _ => null,
     });
 public MockServerClient(string host, int port, string contextPath = "",
                         HttpScheme httpScheme = HttpScheme.Http, HttpClientHandler httpHandler = null)
 {
     _host        = host;
     _port        = port;
     _contextPath = contextPath;
     _httpScheme  = httpScheme;
     _httpClient  = new HttpClient(httpHandler ?? new HttpClientHandler());
 }
 private async Task <HttpResponseMessage> SendHello(HttpScheme scheme)
 {
     using (var client = new HttpClient(Handler, false))
     {
         var host = MockServerClient.ServerAddress().Host;
         var port = MockServerClient.ServerAddress().Port;
         return(await client.GetAsync(new Uri($"{scheme}://{host}:{port}/hello")));
     }
 }
Beispiel #6
0
        public static string Value(this HttpScheme scheme)
        {
            switch (scheme)
            {
            case HttpScheme.Http: return("http");

            case HttpScheme.Https: return("https");

            default: throw new ArgumentOutOfRangeException($"{scheme} is not a valid HTTP scheme");
            }
        }
Beispiel #7
0
        /// <summary>
        /// Returns the standard HTTP scheme for the enum passed in.
        /// </summary>
        /// <param name="httpScheme"></param>
        /// <returns></returns>
        public static string FormatHttpScheme(HttpScheme httpScheme)
        {
            switch (httpScheme)
            {
            case HttpScheme.Http:       return("http");

            case HttpScheme.Https:      return("https");

            case HttpScheme.Unknown:    return(null);

            default:                    throw new NotImplementedException();
            }
        }
        public static string SchemeToString(HttpScheme scheme)
        {
            switch (scheme)
            {
            case HttpScheme.Http:
                return(HttpUriScheme);

            case HttpScheme.Https:
                return(HttpsUriScheme);

            default:
                return(null);
            }
        }
Beispiel #9
0
 public FakeHttpContextBuilder SetRequest(
     HttpMethod method = HttpMethod.Get,
     HttpScheme scheme = HttpScheme.Http,
     Dictionary <string, string>?queryParams   = null,
     Dictionary <string, StringValues>?headers = null)
 {
     return(SetMethod(method)
            .SetScheme(scheme)
            .SetHost(new("localhost"))
            .SetPathBase("/master")
            .SetPath("/slave")
            .SetQuery(queryParams ?? new Dictionary <string, string>())
            .SetRequestHeaders(headers));
 }
Beispiel #10
0
    public static bool GetKnownHttpScheme(this Span <byte> span, out HttpScheme knownScheme)
    {
        if (BinaryPrimitives.TryReadUInt64LittleEndian(span, out var scheme))
        {
            if ((scheme & _mask7Chars) == _httpSchemeLong)
            {
                knownScheme = HttpScheme.Http;
                return(true);
            }

            if (scheme == _httpsSchemeLong)
            {
                knownScheme = HttpScheme.Https;
                return(true);
            }
        }
        knownScheme = HttpScheme.Unknown;
        return(false);
    }
Beispiel #11
0
        private static unsafe bool GetKnownHttpScheme(byte *location, int length, out HttpScheme knownScheme)
        {
            if (length >= sizeof(ulong))
            {
                var scheme = *(ulong *)location;
                if ((scheme & _mask7Chars) == _httpSchemeLong)
                {
                    knownScheme = HttpScheme.Http;
                    return(true);
                }

                if (scheme == _httpsSchemeLong)
                {
                    knownScheme = HttpScheme.Https;
                    return(true);
                }
            }
            knownScheme = HttpScheme.Unknown;
            return(false);
        }
 public HttpForward WithScheme(HttpScheme scheme)
 {
     return(WithScheme(scheme.Value().ToUpper()));
 }
Beispiel #13
0
 public FakeHttpContextBuilder SetScheme(HttpScheme scheme)
 {
     _context.Request.Scheme = scheme.ToString().ToLower();
     return(new FakeHttpContextBuilder(_context));
 }
Beispiel #14
0
        static async Task Main(string[] args)
        {
            ExampleHelper.SetConsoleLogger();

            bool useLibuv = ClientSettings.UseLibuv;

            Console.WriteLine("Transport type : " + (useLibuv ? "Libuv" : "Socket"));

            IEventLoopGroup group;

            if (useLibuv)
            {
                group = new EventLoopGroup();
            }
            else
            {
                group = new MultithreadEventLoopGroup();
            }

            X509Certificate2 cert       = null;
            string           targetHost = null;

            if (ClientSettings.IsSsl)
            {
                cert       = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password");
                targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
            }
            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                .Group(group)
                .Option(ChannelOption.TcpNodelay, true)
                .Option(ChannelOption.SoKeepalive, true);
                if (useLibuv)
                {
                    bootstrap.Channel <TcpChannel>();
                }
                else
                {
                    bootstrap.Channel <TcpSocketChannel>();
                }

                bootstrap.Handler(new Http2ClientFrameInitializer(cert, targetHost));

                IChannel channel = await bootstrap.ConnectAsync(new IPEndPoint(ClientSettings.Host, ClientSettings.Port));

                try
                {
                    Console.WriteLine("Connected to [" + ClientSettings.Host + ':' + ClientSettings.Port + ']');

                    Http2ClientStreamFrameResponseHandler streamFrameResponseHandler =
                        new Http2ClientStreamFrameResponseHandler();

                    Http2StreamChannelBootstrap streamChannelBootstrap = new Http2StreamChannelBootstrap(channel);
                    IHttp2StreamChannel         streamChannel          = await streamChannelBootstrap.OpenAsync();

                    streamChannel.Pipeline.AddLast(streamFrameResponseHandler);

                    // Send request (a HTTP/2 HEADERS frame - with ':method = GET' in this case)
                    var                 path    = ExampleHelper.Configuration["path"];
                    HttpScheme          scheme  = ClientSettings.IsSsl ? HttpScheme.Https : HttpScheme.Http;
                    DefaultHttp2Headers headers = new DefaultHttp2Headers
                    {
                        Method = HttpMethod.Get.AsciiName,
                        Path   = AsciiString.Of(path),
                        Scheme = scheme.Name
                    };
                    IHttp2HeadersFrame headersFrame = new DefaultHttp2HeadersFrame(headers);
                    await streamChannel.WriteAndFlushAsync(headersFrame);

                    Console.WriteLine("Sent HTTP/2 GET request to " + path);

                    // Wait for the responses (or for the latch to expire), then clean up the connections
                    if (!streamFrameResponseHandler.ResponseSuccessfullyCompleted())
                    {
                        Console.WriteLine("Did not get HTTP/2 response in expected time.");
                    }

                    Console.WriteLine("Finished HTTP/2 request, will close the connection.");
                    Console.ReadKey();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    Console.WriteLine("按任意键退出");
                    Console.ReadKey();
                }
                finally
                {
                    // Wait until the connection is closed.
                    await channel.CloseAsync();
                }
            }
            finally
            {
                await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            }
        }
 protected MockServerClientTest(HttpScheme scheme = HttpScheme.Http, HttpClientHandler handler = null)
 {
     MockServerClient = new MockServerClient(_mockServerHost, _mockServerPort,
                                             httpScheme: scheme, httpHandler: handler);
     Assert.True(MockServerClient.IsRunning(), "Server is not running");
 }
Beispiel #16
0
        static async Task Main(string[] args)
        {
            ExampleHelper.SetConsoleLogger();

            bool useLibuv = ClientSettings.UseLibuv;

            Console.WriteLine($"Transport type : {(useLibuv ? "Libuv" : "Socket")}");

            IEventLoopGroup group;

            if (useLibuv)
            {
                group = new EventLoopGroup();
            }
            else
            {
                group = new MultithreadEventLoopGroup();
            }

            X509Certificate2 cert       = null;
            string           targetHost = null;

            if (ClientSettings.IsSsl)
            {
                cert       = new X509Certificate2(Path.Combine(ExampleHelper.ProcessDirectory, "dotnetty.com.pfx"), "password");
                targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
            }

            try
            {
                var bootstrap = new Bootstrap();
                bootstrap
                .Group(group)
                .Option(ChannelOption.TcpNodelay, true);

                if (useLibuv)
                {
                    bootstrap.Channel <TcpChannel>();
                }
                else
                {
                    bootstrap.Channel <TcpSocketChannel>();
                }

                Http2ClientInitializer initializer = new Http2ClientInitializer(cert, targetHost, int.MaxValue);
                bootstrap.Handler(initializer);

                IChannel channel = await bootstrap.ConnectAsync(new IPEndPoint(ClientSettings.Host, ClientSettings.Port));

                try
                {
                    Console.WriteLine($"Connected to [{ClientSettings.Host}:{ClientSettings.Port}]");

                    // Wait for the HTTP/2 upgrade to occur.
                    Http2SettingsHandler http2SettingsHandler = initializer.SettingsHandler;
                    await http2SettingsHandler.AwaitSettings(TimeSpan.FromSeconds(5));

                    HttpResponseHandler responseHandler = initializer.ResponseHandler;
                    int         streamId = 3;
                    HttpScheme  scheme   = ClientSettings.IsSsl ? HttpScheme.Https : HttpScheme.Http;
                    AsciiString hostName = new AsciiString(ClientSettings.Host.ToString() + ':' + ClientSettings.Port);
                    Console.WriteLine("Sending request(s)...");

                    var url      = ExampleHelper.Configuration["url"];
                    var url2     = ExampleHelper.Configuration["url2"];
                    var url2Data = ExampleHelper.Configuration["url2data"];

                    if (!string.IsNullOrEmpty(url))
                    {
                        // Create a simple GET request.
                        IFullHttpRequest request = new DefaultFullHttpRequest(DotNetty.Codecs.Http.HttpVersion.Http11, HttpMethod.Get, url, Unpooled.Empty);
                        request.Headers.Add(HttpHeaderNames.Host, hostName);
                        request.Headers.Add(HttpConversionUtil.ExtensionHeaderNames.Scheme, scheme.Name);
                        request.Headers.Add(HttpHeaderNames.AcceptEncoding, HttpHeaderValues.Gzip);
                        request.Headers.Add(HttpHeaderNames.AcceptEncoding, HttpHeaderValues.Deflate);
                        responseHandler.Put(streamId, channel.WriteAsync(request), channel.NewPromise());
                        streamId += 2;
                    }

                    if (!string.IsNullOrEmpty(url2))
                    {
                        // Create a simple POST request with a body.
                        IFullHttpRequest request = new DefaultFullHttpRequest(DotNetty.Codecs.Http.HttpVersion.Http11, HttpMethod.Post, url2,
                                                                              Unpooled.WrappedBuffer(Encoding.UTF8.GetBytes(url2Data)));
                        request.Headers.Add(HttpHeaderNames.Host, hostName);
                        request.Headers.Add(HttpConversionUtil.ExtensionHeaderNames.Scheme, scheme.Name);
                        request.Headers.Add(HttpHeaderNames.AcceptEncoding, HttpHeaderValues.Gzip);
                        request.Headers.Add(HttpHeaderNames.AcceptEncoding, HttpHeaderValues.Deflate);
                        responseHandler.Put(streamId, channel.WriteAsync(request), channel.NewPromise());
                    }

                    channel.Flush();
                    await responseHandler.AwaitResponses(TimeSpan.FromSeconds(5));

                    Console.WriteLine("Finished HTTP/2 request(s)");
                    Console.ReadKey();
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.ToString());
                    Console.WriteLine("Press any key to exit");
                    Console.ReadKey();
                }
                finally
                {
                    // Wait until the connection is closed.
                    await channel.CloseAsync();
                }
            }
            finally
            {
                await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            }
        }
Beispiel #17
0
 public void Start(int port, HttpScheme scheme = HttpScheme.Http)
 {
     Start($"{scheme.ToString().ToLower()}://+:{port}/");
 }