vs2013和.net 4.5.1调用.net core中的Kestrel(基于libuv)的http服务器代码 两种方式
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服务器代码 两种方式的更多相关文章
- C#动态调用WCF接口,两种方式任你选。
写在前面 接触WCF还是它在最初诞生之处,一个分布式应用的巨作. 从开始接触到现在断断续续,真正使用的项目少之又少,更谈不上深入WCF内部实现机制和原理去研究,最近自己做一个项目时用到了WCF. 从这 ...
- java中调用本地动态链接库(*.DLL)的两种方式详解和not found library、打包成jar,war包dll无法加载等等问题解决办法
我们经常会遇到需要java调用c++的案例,这里就java调用DLL本地动态链接库两种方式,和加载过程中遇到的问题进行详细介绍 1.通过System.loadLibrary("dll名称,不 ...
- springcloud 服务调用的两种方式
spring-cloud调用服务有两种方式,一种是Ribbon+RestTemplate, 另外一种是Feign.Ribbon是一个基于HTTP和TCP客户端的负载均衡器,其实feign也使用了rib ...
- javascript消除字符串两边空格的两种方式,面向对象和函数式编程。python oop在调用时候的优点
主要是javascript中消除字符串空格,比较两种方式的不同 //面向对象,消除字符串两边空格 String.prototype.trim = function() { return this.re ...
- DLL调用的两种方式(IDE:VC6.0,C++)
原文:http://www.cnblogs.com/Pickuper/articles/2050409.html DLL调用有两种方式,一种是静态调用,另外一种是动态调用 (一)静态调用 静态调用是一 ...
- 调用init方法 两种方式 一个是浏览器方法 一个是 xml中手工配置(load-on-startup)
调用init方法 两种方式 一个是浏览器方法 一个是 xml中手工配置(load-on-startup)
- 通过调用C语言的库函数与在C代码中使用内联汇编两种方式来使用同一个系统调用来分析系统调用的工作机制
通过调用C语言的库函数与在C代码中使用内联汇编两种方式来使用同一个系统调用来分析系统调用的工作机制 前言说明 本篇为网易云课堂Linux内核分析课程的第四周作业,我将通过调用C语言的库函数与在C代码中 ...
- Unity调用Android的两种方式:其一、调用jar包
unity在Android端开发的时候,免不了要调用Java:Unity可以通过两种方式来调用Android:一是调用jar.二是调用aar. 这篇文章主要讲解怎么从无到有的生成一个jar包,然后un ...
- Spring容器自动调用方法的两种方式
先看一个Spring中Bean的实例化过程: 1.配置文件中指定Bean的init-method参数 <bean class="com.jts.service.UserService& ...
随机推荐
- No bean named 'hibernateTemplate' is defined
1.错误描述 WARN:2015-05-01 15:42:22[localhost-startStop-1] - Exception encountered during context initia ...
- Linux显示2015年日历表
Linux显示2015年日历表 youhaidong@youhaidong-ThinkPad-Edge-E545:~$ cal 2015 2015 一月 二月 三月 日 一 二 三 四 五 六 日 一 ...
- LeetCode 542. 01 Matrix
输入:只包含0,1的矩阵 输出:元素1到达最近0的距离 算法思想:广度优先搜索. 元素为0为可达区域,元素为1为不可达区域,我们的目标是为了从可达区域不断地扩展至不可达区域,在扩展的过程中,也就计算出 ...
- ASP.NET CORE的Code Fist后Models更改了怎么办?
上次我写到MVC的code fist后,自动生成数据库并自动生成web页面了 点击打开链接 那么随着项目需求的逐步明确,model变化了怎么办呢?其实和上次一样的,有两条关键的语句要记住 Add-Mi ...
- 手机端仿ios的三级联动脚本四
二,脚本 <script> $("#city-picker").cityPicker({ title: "选择省市区/县", onChange: f ...
- 利用shell脚本实现对mysql数据库的备份
#!/bin/bash #保存备份个数 number=3 #备份保存路径 backup_dir=/root/mysqlbackup #日期 dd=`date +%Y%m%d` #备份工具 tool=m ...
- SpringMVC国际化支持
这周公司领导希望我对一个项目,出一个国际化的解决方案,研究两个小时,采用了SpringMVC的国际化支持,在此记录下. 原理: 在DispatchServlet中注册localeResolver(区域 ...
- Oracle11g客户端client的下载与安装
下载地址: http://www.oracle.com/technetwork/database/enterprise-edition/downloads/112010-win64soft-09446 ...
- 如何降低90%Java垃圾回收时间?以阿里HBase的GC优化实践为例
过去的一年里,我们准备在Ali-HBase上突破这个被普遍认知的痛点,为此进行了深度分析及全面创新的工作,获得了一些比较好的效果.以蚂蚁风控场景为例,HBase的线上young GC时间从120ms减 ...
- ASP.NET Core 一步步搭建个人网站(7)_Linux系统移植
摘要 考虑我们为什么要选择.NET Core? 因为它面向的是高性能服务器开发,抛却了 AspNet 的臃肿组件,非常轻量,加上微软的跨平台战略,对 Docker 的亲和性,对于开发人员也非常友好,所 ...