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& ...
随机推荐
- Looks like the Spring listener was not configured for your web app!
1.错误描述 usage: java org.apache.catalina.startup.Catalina [ -config {pathname} ] [ -nonaming ] { -help ...
- AVStream ddk 翻译
1. AVStream概览 AVStream是一款微软提供的多媒体类驱动程序,它既支持单独的视频流媒体,也支持音频视频集成的流媒体.微软把AVStream作为操作系统的一部分,在驱动程序k ...
- 芝麻HTTP:redis-py的安装
对于Redis来说,我们要使用redis-py库来与其交互,这里就来介绍一下它的安装方法. 1. 相关链接 GitHub:https://github.com/andymccurdy/redis-py ...
- 主流nosql数据库对比
目前开源的NOSQL数据库有,Redis,Tokyo Cabinet,Cassandra,Voldemort,MongoDB,Dynomite,HBase,CouchDB,Hypertable, Ri ...
- 【BZOJ3670】动物园(KMP算法)
[BZOJ3670]动物园(KMP算法) 题面 BZOJ 题解 神TM阅读理解题 看完题目之后 想暴力: 搞个倍增数组来跳\(next\) 每次暴跳\(next\) 复杂度\(O(Tnlogn)\) ...
- css块级元素和内联元素
左边的是块级元素block,右边内联inline. 修改方法 display: inline;
- python3下Django2.0配置最新xadmin详解
1,打开pycharm,创建一个Django项目 2,安装Django,默认是最新版本,pip3 install -i https://pypi.douban.com/simple/ django 3 ...
- 接收JSON类型转成对象
写个小例子吧: public String getJsonTest(String jsonString){} 参数是json 参数长这样 ===> { 'puser' : {'id' : ' ...
- FTP环境搭建及客户代码调用公共方法封装
一.背景 大型系统架构往往被分解为多个独立可运行的组件, 以满足性能.可靠性.可扩展性的需求.多个组件间的数据交互往往采用两种方式:小量数据通过Sock函数.RMI.WebService等接口方式传递 ...
- c++中回调函数和函数指针的使用
#include "stdafx.h" #include <iostream> //#include <string> using namespace st ...