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. Django学习-22-Form

    Form是Django的功能较强的验证组件,负责各种表单验证 input中的name属性值要和form中的字段名相同 from django import forms from django.form ...

  2. 异常-----freemarker.template.TemplateException:Error executing macro:mainSelect

    1.错误描述 freemarker.template.TemplateException:Error executing macro:mainSelect require parameter:id i ...

  3. 在TextBox中敲击回车执行ASP.NET后台事件

    1.在TextBox中敲击回车执行ASP.NET后台事件   0.说明 页面中有一个用于搜索的TextBox,希望能在输入内容后直接回车开始搜索,而不是手动去点击它旁边的搜索按钮 但因为该TextBo ...

  4. jquery 记住账号 记住密码

    <body> <label><input type="checkbox" onclick="loginBtn_user()" /& ...

  5. Ubuntu出现ERR_PROXY_CONNECTION_FAILED错误解决方案

    我是Ubuntu新手,因为想查看国外的资料,然后安装了灯笼,结果打开谷歌浏览器出现了ERR_PROXY_CONNECTION_FAILED错误,未连接到互联网,代理服务器出现错误,然后Firefox也 ...

  6. Weex 初探

    Weex 初探 Weex 介绍 Weex 是阿里于 2016 年开源的一款开发框架,它的介绍是: Weex 是一个使用 Web 开发体验来开发高性能原生应用的框架. 它使用了 Web 技术来开发 An ...

  7. 【BZOJ2134】单位错选(数学期望,动态规划)

    [BZOJ2134]单位错选(数学期望,动态规划) 题面 BZOJ 题解 单独考虑相邻的两道题目的概率就好了 没了呀.. #include<iostream> #include<cs ...

  8. 【BZOJ4530】大融合(Link-Cut Tree)

    [BZOJ4530]大融合(Link-Cut Tree) 题面 讨厌权限题!!! Loj链接 题目描述 小强要在 N个孤立的星球上建立起一套通信系统.这套通信系统就是连接 N个点的一个树.这个树的边是 ...

  9. css实现文本缩略显示

    转载自http://blog.csdn.net/mushui0633/article/details/65685655 单行: 对应的css中加入 overflow:hidden;//超出一行文字自动 ...

  10. github远程仓库初始化配置

    github远程仓库的提交一般是通过shell进行,windows下有Git Bash工具(https://git-for-windows.github.io/) 由于本地Git仓库和GitHub仓库 ...