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& ...
随机推荐
- Linux显示各栏位的标题信息列
Linux显示各栏位的标题信息列 youhaidong@youhaidong-ThinkPad-Edge-E545:~$ who -H 名称 线路 时间 备注 youhaidong :0 2015-0 ...
- Flex中TabNavigator隐藏和显示选项卡
1.问题背景 遇到这样一个问题:有四个Tab选项卡,根据不同的参数隐藏和显示选项卡 2.实现实例 (1)隐藏"春季" protected function springClickH ...
- 基于jQuery的一个提示功能的实现
最近有点忙,没有时间更新自己的博客,只能说我在原地踏步了,不知道你们进步了没有? 今天给大家分享一个提示的实现,有点简单,适合小白同学学习.下面是效果图 提示的功能: 当鼠标进入“我的菜单”的子菜单时 ...
- java,while循环的使用,接收用户的输入,进行不同的操作!
package cn.edu.nwpu.java; import java.util.Scanner; public class IsoscelesTriangle { public static v ...
- Python与Mongodb交互
MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统 MongoDB 旨在为WEB应用提供可扩展的高性能数据存储解决方案 MongoDB 将数据存储为一个文档,数据结构由键值 ...
- 算法精解:DAG有向无环图
DAG是公认的下一代区块链的标志.本文从算法基础去研究分析DAG算法,以及它是如何运用到区块链中,解决了当前区块链的哪些问题. 关键字:DAG,有向无环图,算法,背包,深度优先搜索,栈,BlockCh ...
- sql性能优化之多表联查
先贴上我优化后的核心代码: select * into #result from ( select p.AchivementCount,isnull(a.ByAttentionCount,0) ByA ...
- 微信小程序初探【类微信UI聊天简单实现】
微信小程序最近很火,火到什么程度,只要你一打开微信,就是它的身影,几乎你用的各个APP都可以在微信中找到它的复制版,另外官方自带的跳一跳更是将它推到了空前至高的位置.对比公众号,就我的感觉来说,有以下 ...
- 线段树 (区间查询最大 区间求和 区间加)带lazy
; struct Segment_tree { struct Node { int val,Max,lazy; ]; void init() { lazy=son[]=son[]=Size=val=M ...
- Oracle用户、授权、角色管理
创建和删除用户是Oracle用户管理中的常见操作,但这其中隐含了Oracle数据库系统的系统权限与对象权限方面的知识.掌握还Oracle用户的授权操作和原理,可以有效提升我们的工作效率. Oracle ...