nuget获取相关的包:两个:Microsoft.AspNetCore.Server.Kestrel 和 Microsoft.Extensions.Logging.Console

编译完成后手工将package 中的libuv下的libuv.dll拷贝到你的exe目录。

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KingUvHttp
{
    class Program
    {
        static void Main(string[] args)
        {
            Http1();
            Http2();
        }

static void Http1()
        {
            UvHttpServer server = new UvHttpServer();
            //注意,这里不能用"localhost"这种,必须是明确的ip地址。
            server.Addresses.Add("http://0.0.0.0:5000");
            var app = new HxzHttpApplication();
            server.Start(app);
            
        }

static void Http2()
        {
            var host = new WebHostBuilder()
                .UseKestrel(options =>
                {
                    // options.ThreadCount = 4;
                    options.NoDelay = true;
                    options.UseConnectionLogging();
                })
                .UseUrls("http://127.0.0.1:5001")
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>()
                .Build();
            host.Run();
        }
    }

public class Startup
    {
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(LogLevel.Trace);

app.Run(async context =>
            {
                Console.WriteLine("{0} {1}{2}{3}",
                    context.Request.Method,
                    context.Request.PathBase,
                    context.Request.Path,
                    context.Request.QueryString);
                Console.WriteLine("Method:{0}",context.Request.Method);
                Console.WriteLine("PathBase:{0}",context.Request.PathBase);
                Console.WriteLine("Path:{0}",context.Request.Path);
                Console.WriteLine("QueryString:{0}",context.Request.QueryString);

var connectionFeature = context.Connection;
                Console.WriteLine("Peer:{0}",connectionFeature.RemoteIpAddress.ToString());
                Console.WriteLine("Sock:{0}",connectionFeature.LocalIpAddress.ToString());

context.Response.ContentLength = 11;
                context.Response.ContentType = "text/plain";
                await context.Response.WriteAsync("Hello world");
            });
        }
    }
}
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Server.Kestrel;
using Microsoft.AspNetCore.Server.Kestrel.Internal;
using Microsoft.AspNetCore.Server.Kestrel.Internal.Http;
using Microsoft.AspNetCore.Server.Kestrel.Internal.Infrastructure;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KingUvHttp
{
    public class UvHttpServer
    {
        private Stack<IDisposable> _disposables;

public UvHttpServer()
        {
            Options = new KestrelServerOptions();
            Addresses = new List<string>();
            lf.AddConsole();
            _logger = lf.CreateLogger("UvHttpServer");
        }
        public LoggerFactory lf = new LoggerFactory();
        public HxzApplicationLifetime AppLt { get; set; }
        public KestrelServerOptions Options { get; set; }
        public List<string> Addresses { get; set; }
        public ILogger _logger { get; set; }
        public void Start<TContext>(IHttpApplication<TContext> application)
        {
            if (_disposables != null)
            {
                // The server has already started and/or has not been cleaned up yet
                throw new InvalidOperationException("Server has already started.");
            }
            _disposables = new Stack<IDisposable>();

try
            {
                var dateHeaderValueManager = new DateHeaderValueManager();
                var trace = new KestrelTrace(_logger);
                var engine = new KestrelEngine(new ServiceContext
                {
                    FrameFactory = context =>
                    {
                        return new Frame<TContext>(application, context);
                    },
                    AppLifetime = AppLt,
                    Log = trace,
                    ThreadPool = new LoggingThreadPool(trace),
                    DateHeaderValueManager = dateHeaderValueManager,
                    ServerOptions = Options
                });

_disposables.Push(engine);
                _disposables.Push(dateHeaderValueManager);

var threadCount = Options.ThreadCount;

if (threadCount <= 0)
                {
                    throw new ArgumentOutOfRangeException("threadCount",
                        threadCount,
                        "ThreadCount must be positive.");
                }

engine.Start(threadCount);
                var atLeastOneListener = false;

foreach (var address in Addresses.ToArray())
                {
                    var parsedAddress = ServerAddress.FromUrl(address);
                    atLeastOneListener = true;
                    _disposables.Push(engine.CreateServer(parsedAddress));
                    Addresses.Remove(address);
                    Addresses.Add(parsedAddress.ToString());
                }

if (!atLeastOneListener)
                {
                    throw new InvalidOperationException("No recognized listening addresses were configured.");
                }
            }
            catch (Exception e)
            {
                Dispose();
                throw;
            }
        }

public void Dispose()
        {
            if (_disposables != null)
            {
                while (_disposables.Count > 0)
                {
                    _disposables.Pop().Dispose();
                }
                _disposables = null;
            }
        }
    }
}

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel;
using Microsoft.AspNetCore.Server.Kestrel.Internal.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace KingUvHttp
{
    public class HttpCtx
    {
        public Frame<HttpCtx> frame { get; set; }
    }

public class HxzHttpApplication : IHttpApplication<HttpCtx>
    {
        public HttpCtx CreateContext(IFeatureCollection contextFeatures)
        {
            HttpCtx ctx = new HttpCtx();
            ctx.frame = (Frame<HttpCtx>)contextFeatures;
            return ctx;
        }

public void DisposeContext(HttpCtx context, Exception exception)
        {
        }

public Task ProcessRequestAsync(HttpCtx context)
        {
            Console.WriteLine("Method:{0}", context.frame.Method);
            Console.WriteLine("PathBase:{0}", context.frame.PathBase);
            Console.WriteLine("Path:{0}", context.frame.Path);
            Console.WriteLine("QueryString:{0}", context.frame.QueryString);

Console.WriteLine("Peer:{0}", context.frame.RemoteEndPoint.ToString());
            Console.WriteLine("Sock:{0}", context.frame.LocalEndPoint.ToString());

return Task.Factory.StartNew(() =>
            {

var enc = System.Text.Encoding.UTF8;
                byte[] rspbin = enc.GetBytes("hello,world");
                context.frame.ResponseBody.WriteAsync(rspbin, 0, rspbin.Length);
            });
        }
    }

public class HxzServiceProvider : IServiceProvider
    {
        public object GetService(Type serviceType)
        {
            if (serviceType == typeof(ILoggerFactory))
            {
                return ilf;
            }
            return null;
        }
        private static ILoggerFactory ilf = new LoggerFactory();
    }

public class HxzApplicationLifetime : IApplicationLifetime
    {
        public CancellationToken ApplicationStarted
        {
            get
            {
                throw new NotImplementedException();
            }
        }

public CancellationToken ApplicationStopped
        {
            get
            {
                throw new NotImplementedException();
            }
        }

public CancellationToken ApplicationStopping
        {
            get
            {
                throw new NotImplementedException();
            }
        }

public void StopApplication()
        {
            throw new NotImplementedException();
        }
    }

public class HxzOptions : IOptions<KestrelServerOptions>
    {
        public KestrelServerOptions Value { get; set; }
    }
}

vs2013和.net 4.5.1调用.net core中的Kestrel(基于libuv)的http服务器代码 两种方式的更多相关文章

  1. C#动态调用WCF接口,两种方式任你选。

    写在前面 接触WCF还是它在最初诞生之处,一个分布式应用的巨作. 从开始接触到现在断断续续,真正使用的项目少之又少,更谈不上深入WCF内部实现机制和原理去研究,最近自己做一个项目时用到了WCF. 从这 ...

  2. java中调用本地动态链接库(*.DLL)的两种方式详解和not found library、打包成jar,war包dll无法加载等等问题解决办法

    我们经常会遇到需要java调用c++的案例,这里就java调用DLL本地动态链接库两种方式,和加载过程中遇到的问题进行详细介绍 1.通过System.loadLibrary("dll名称,不 ...

  3. springcloud 服务调用的两种方式

    spring-cloud调用服务有两种方式,一种是Ribbon+RestTemplate, 另外一种是Feign.Ribbon是一个基于HTTP和TCP客户端的负载均衡器,其实feign也使用了rib ...

  4. javascript消除字符串两边空格的两种方式,面向对象和函数式编程。python oop在调用时候的优点

    主要是javascript中消除字符串空格,比较两种方式的不同 //面向对象,消除字符串两边空格 String.prototype.trim = function() { return this.re ...

  5. DLL调用的两种方式(IDE:VC6.0,C++)

    原文:http://www.cnblogs.com/Pickuper/articles/2050409.html DLL调用有两种方式,一种是静态调用,另外一种是动态调用 (一)静态调用 静态调用是一 ...

  6. 调用init方法 两种方式 一个是浏览器方法 一个是 xml中手工配置(load-on-startup)

    调用init方法 两种方式 一个是浏览器方法 一个是 xml中手工配置(load-on-startup)

  7. 通过调用C语言的库函数与在C代码中使用内联汇编两种方式来使用同一个系统调用来分析系统调用的工作机制

    通过调用C语言的库函数与在C代码中使用内联汇编两种方式来使用同一个系统调用来分析系统调用的工作机制 前言说明 本篇为网易云课堂Linux内核分析课程的第四周作业,我将通过调用C语言的库函数与在C代码中 ...

  8. Unity调用Android的两种方式:其一、调用jar包

    unity在Android端开发的时候,免不了要调用Java:Unity可以通过两种方式来调用Android:一是调用jar.二是调用aar. 这篇文章主要讲解怎么从无到有的生成一个jar包,然后un ...

  9. Spring容器自动调用方法的两种方式

    先看一个Spring中Bean的实例化过程: 1.配置文件中指定Bean的init-method参数 <bean class="com.jts.service.UserService& ...

随机推荐

  1. JSP路径出现问题

    1.错误描述 2.错误原因 <%@ page language="java" import="java.util.*" pageEncoding=&quo ...

  2. winhex中判断+MBR+DBR+EBR方法

    [/hide] 扇区开始描述). 用 winhex 做U盘免疫AUTO.INF 用WinHex制作无法修改的AutoRun.inf文件 在我们日常工作中,经常需要使用闪存(也称为U盘或者优盘)主要是A ...

  3. Request对象实现请求转发区别

    servlet请求转发与重定向的区别: request.setAttribute("test","hello"); request.getRequestDisp ...

  4. 一个2D平面游戏,的碰撞引擎实现

    @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); i ...

  5. Java高并发之从零到放弃

    前言 本篇主要讲解如何去优化锁机制或者克服多线程因为锁可导致性能下降的问题 ThreadLocal线程变量 有这样一个场景,前面是一大桶水,10个人去喝水,为了保证线程安全,我们要在杯子上加锁导致大家 ...

  6. ssm整合快速入门程序(三)之Data类型转换器

    今天就写写springmvc配置Data类型转换器 首先在创建一个转换器的包cn.my.ssm.controller.converter,创建一个CustomDateConverter类实现Conve ...

  7. [SCOI2005]王室联邦

    分块基本没有限制 所以每次大于等于b就分一块 # include <bits/stdc++.h> # define RG register # define IL inline # def ...

  8. Java 计算年龄

    public static String getAgeTxt(String birthTime,String beginTime,int level){ if(StringUtils.isBlank( ...

  9. Filter的过滤链理解

    一.Filter过滤链 web.xml配置了filter过滤器,在容器启动的时候执行了init()方法进行了初始化,然后在容器关闭的时候执行了destroy()方法销毁过滤器,在每次服务器接受请求的时 ...

  10. hadoop2.x源码编译

    转载请标明出处: http://blog.csdn.net/zwto1/article/details/50733753: 介绍 本篇主要会涉及以下内容: 学会编译hadoop2.x源码 编译hado ...