├── Demo
├── Nancy.Demo2
│ ├── MyStatusHandler.cs
│ ├── Views
│ │ ├── Test.cshtml
│ │ ├── Home
│ │ │ └── Index.cshtml
│ │ └── Status
│ │ │ └── 404.cshtml
│ ├── BootStrapper.cs
│ ├── Startup.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── RazorConfig.cs
│ ├── Web.Debug.config
│ ├── Web.config
│ ├── MainModule.cs
│ ├── Web.Release.config
│ ├── SiteRootPath.cs
│ ├── Adapter.cs
│ └── Nancy.Demo2.csproj
├── AspTest
│ ├── aspx
│ │ ├── Default.aspx
│ │ └── Default.aspx.cs
│ ├── Adapter.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ └── AspTest.csproj
└── WebSocket.Demo2
│ ├── Properties
│ └── AssemblyInfo.cs
│ ├── index.html
│ ├── WebSocket.Demo2.csproj
│ └── Adapter.cs
├── OwinDog
├── runtime
│ └── native
│ │ └── libuv
│ │ ├── oth
│ │ └── libuv.dylib
│ │ ├── lin
│ │ └── x32
│ │ │ └── libuv.so.1
│ │ └── win
│ │ └── x32
│ │ └── libuv.dll
├── Service
│ ├── WriteParam.cs
│ ├── CustomeAsyncResult.cs
│ ├── RequestDataFactory.cs
│ ├── RequestCheck.cs
│ ├── ApplicationInfo.cs
│ ├── ActionQueue.cs
│ ├── ActionStoreManage.cs
│ ├── SimpleThreadPool.cs
│ └── HttpMimeTypeManage.cs
├── OwinEngine
│ ├── OwinHttpWorkerManage.cs
│ ├── OwinAdapterManage.cs
│ ├── ISocket.cs
│ ├── HeaderDictionary.cs
│ ├── OwinAdapter.cs
│ ├── OwinTask.cs
│ └── OwinRequestStream.cs
├── ProgMain.cs
├── Model
│ ├── UvPipeHandle.cs
│ ├── LoopHandle.cs
│ ├── ListenHandle.cs
│ ├── AsyncHandle.cs
│ ├── UvPipeStream.cs
│ ├── ShutdownHandle.cs
│ ├── HandleBase.cs
│ ├── WriteHandle.cs
│ └── UvStreamHandle.cs
├── Properties
│ └── AssemblyInfo.cs
├── Util
│ ├── HttpCodeUtil.cs
│ ├── SystemUtil.cs
│ ├── UrlDeCode.cs
│ ├── WebSocketReciveDataParse.cs
│ └── AssemblyUtils.cs
└── OwinDog.csproj
├── Dog
├── App.config
├── Properties
│ └── AssemblyInfo.cs
└── Dog.csproj
├── Owin.WebSocket
├── packages.config
├── WebSocketRouteAttribute.cs
├── Handlers
│ ├── SendContext.cs
│ ├── IWebSocket.cs
│ ├── NetWebSocket.cs
│ └── OwinWebSocket.cs
├── Properties
│ └── AssemblyInfo.cs
├── WebSocketConnectionMiddleware.cs
├── Extensions
│ ├── OwinExtension.cs
│ └── TaskQueue.cs
└── Owin.WebSocket.csproj
├── README.md
├── Owin.AspEngine
├── Properties
│ └── AssemblyInfo.cs
├── AspEngine
│ ├── AspRequestData.cs
│ ├── AspRequestBroker.cs
│ ├── AspApplicationHost.cs
│ └── AspNet.cs
└── Owin.AspEngine.csproj
└── .gitignore
/Demo/Nancy.Demo2/MyStatusHandler.cs:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yuzd/OwinDog/HEAD/Demo/Nancy.Demo2/MyStatusHandler.cs
--------------------------------------------------------------------------------
/OwinDog/runtime/native/libuv/oth/libuv.dylib:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yuzd/OwinDog/HEAD/OwinDog/runtime/native/libuv/oth/libuv.dylib
--------------------------------------------------------------------------------
/OwinDog/runtime/native/libuv/lin/x32/libuv.so.1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yuzd/OwinDog/HEAD/OwinDog/runtime/native/libuv/lin/x32/libuv.so.1
--------------------------------------------------------------------------------
/OwinDog/runtime/native/libuv/win/x32/libuv.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yuzd/OwinDog/HEAD/OwinDog/runtime/native/libuv/win/x32/libuv.dll
--------------------------------------------------------------------------------
/Demo/Nancy.Demo2/Views/Test.cshtml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | 参数是:@Model.abc
8 |
9 |
10 |
--------------------------------------------------------------------------------
/Dog/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Demo/Nancy.Demo2/Views/Home/Index.cshtml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Index
5 |
6 |
7 | Hello.....
8 |
9 |
10 |
--------------------------------------------------------------------------------
/Demo/Nancy.Demo2/Views/Status/404.cshtml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | 404, Can't find....
8 |
9 |
10 |
--------------------------------------------------------------------------------
/OwinDog/Service/WriteParam.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Service
4 | {
5 | public sealed class WriteParam
6 | {
7 | public byte[] Buffer;
8 |
9 | public int Offset;
10 |
11 | public int Length;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/Owin.WebSocket/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Owin.WebSocket/WebSocketRouteAttribute.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Owin.WebSocket
4 | {
5 | [AttributeUsage(AttributeTargets.Class, AllowMultiple=true)]
6 | public class WebSocketRouteAttribute: Attribute
7 | {
8 | public string Route { get; set; }
9 |
10 | public WebSocketRouteAttribute(string route)
11 | {
12 | Route = route;
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Demo/Nancy.Demo2/BootStrapper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Web;
5 | using Nancy.Session;
6 | namespace Nancy.Demo2
7 | {
8 | public class BootStrapper : DefaultNancyBootstrapper
9 | {
10 | protected override void ApplicationStartup(TinyIoc.TinyIoCContainer container, Bootstrapper.IPipelines pipelines)
11 | {
12 | //启用session
13 | CookieBasedSessions.Enable(pipelines);
14 | }
15 | }
16 | }
--------------------------------------------------------------------------------
/OwinDog/OwinEngine/OwinHttpWorkerManage.cs:
--------------------------------------------------------------------------------
1 | using Service;
2 |
3 | namespace OwinEngine
4 | {
5 | public static class OwinHttpWorkerManage
6 | {
7 | public static void OwinHttpProcess(OwinSocket owinSocket)
8 | {
9 | new OwinHttpWorker(null).Start(owinSocket);
10 | }
11 |
12 | public static void Start(OwinSocket owinSocket, byte[] array)
13 | {
14 | new OwinHttpWorker(array).Start(owinSocket);
15 | }
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/Demo/AspTest/aspx/Default.aspx:
--------------------------------------------------------------------------------
1 | <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/OwinDog/ProgMain.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Diagnostics;
4 | using System.IO;
5 | using System.Linq;
6 | using System.Net.Sockets;
7 | using System.Reflection;
8 | using System.Runtime.CompilerServices;
9 | using System.Runtime.InteropServices;
10 | using System.Text;
11 | using System.Threading;
12 | using System.Threading.Tasks;
13 | using System.Timers;
14 | using Model;
15 | using OwinEngine;
16 | using Service;
17 | using Util;
18 |
19 | namespace OwinDog
20 | {
21 | public class ProgMain
22 | {
23 |
24 |
25 | }
26 |
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/Owin.WebSocket/Handlers/SendContext.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Net.WebSockets;
3 | using System.Threading;
4 |
5 | namespace Owin.WebSocket.Handlers
6 | {
7 | internal class SendContext
8 | {
9 | public ArraySegment Buffer;
10 | public bool EndOfMessage;
11 | public WebSocketMessageType Type;
12 | public CancellationToken CancelToken;
13 |
14 | public SendContext(ArraySegment buffer, bool endOfMessage, WebSocketMessageType type, CancellationToken cancelToken)
15 | {
16 | Buffer = buffer;
17 | EndOfMessage = endOfMessage;
18 | Type = type;
19 | CancelToken = cancelToken;
20 | }
21 | }
22 | }
--------------------------------------------------------------------------------
/Demo/AspTest/Adapter.cs:
--------------------------------------------------------------------------------
1 |
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Net.WebSockets;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 | using Owin.AspEngine;
8 |
9 | namespace AspTest
10 | {
11 |
12 | ///
13 | /// owin/owindog For OWIN 接口类
14 | ///
15 | public class Adapter
16 | {
17 |
18 |
19 | ///
20 | /// OWIN适配器的主函数
21 | ///
22 | ///
23 | ///
24 | public Task OwinMain(IDictionary env)
25 | {
26 |
27 | return AspNet.Process(env);
28 | }
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 | }
38 |
39 |
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/OwinDog/Model/UvPipeHandle.cs:
--------------------------------------------------------------------------------
1 |
2 | namespace Model
3 | {
4 |
5 | public class UvPipeHandle : UvStreamHandle
6 | {
7 | public int PipePendingCount()
8 | {
9 | return LibUv.PipePendingCount(this);
10 | }
11 |
12 | public void PipeBind(string text)
13 | {
14 | LibUv.PipeBind(this, text);
15 | }
16 |
17 | ///
18 | /// Init
19 | ///
20 | ///
21 | /// 若是 IPC 或命名管道,应该设置为 true
22 | public void Init(LoopHandle loopHandle, bool flag = true)
23 | {
24 | Init(loopHandle.LibUv, loopHandle.LibUv.NamePipeHandleSize, loopHandle.LoopRunThreadId);
25 | LibUv.PipeInit(loopHandle, this, flag);
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Demo/Nancy.Demo2/Startup.cs:
--------------------------------------------------------------------------------
1 | using Owin;
2 | using Nancy;
3 |
4 | namespace Nancy.Demo2
5 | {
6 |
7 | ///
8 | /// 支持NancyFx的OWIN启动类
9 | /// MS'OWIN 标准的宿主都需要一个启动类
10 | ///
11 | public class Startup
12 | {
13 | public Startup() {
14 |
15 | // 显示详细的异常信息
16 | StaticConfiguration.DisableErrorTraces = false;
17 |
18 | //增加Nancy处理json字串的长度
19 | //Nancy.Json.JsonSettings.MaxJsonLength = int.MaxValue;
20 |
21 | // 其它初始化动作
22 | // ........
23 | }
24 |
25 | public void Configuration(IAppBuilder builder)
26 | {
27 | //将 Nancy(中间件)添加到Microsoft.Owin处理环节中
28 | ////////////////////////////////////////////////////
29 | builder.UseNancy();
30 |
31 | }
32 | }
33 |
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/Owin.WebSocket/Handlers/IWebSocket.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Net.WebSockets;
3 | using System.Threading;
4 | using System.Threading.Tasks;
5 | using Owin.WebSocket.Extensions;
6 |
7 | namespace Owin.WebSocket.Handlers
8 | {
9 | internal interface IWebSocket
10 | {
11 | TaskQueue SendQueue { get; }
12 | Task SendText(ArraySegment data, bool endOfMessage, CancellationToken cancelToken);
13 | Task SendBinary(ArraySegment data, bool endOfMessage, CancellationToken cancelToken);
14 | Task Send(ArraySegment data, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancelToken);
15 | Task Close(WebSocketCloseStatus closeStatus, string closeDescription, CancellationToken cancelToken);
16 | Task, WebSocketMessageType>> ReceiveMessage(byte[] buffer, CancellationToken cancelToken);
17 | WebSocketCloseStatus? CloseStatus { get; }
18 | string CloseStatusDescription { get; }
19 | }
20 | }
--------------------------------------------------------------------------------
/Demo/AspTest/aspx/Default.aspx.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text.RegularExpressions;
5 | using System.Web;
6 | using System.Web.UI;
7 | using System.Web.UI.WebControls;
8 |
9 | public partial class _Default : System.Web.UI.Page
10 | {
11 | protected void Page_Load(object sender, EventArgs e)
12 | {
13 | this.ipTxt.Value = GetIp();
14 | }
15 |
16 | public string GetIp()
17 | {
18 | string result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
19 | result += "," + HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
20 |
21 | result += "," + HttpContext.Current.Request.UserHostAddress;
22 |
23 | if (string.IsNullOrEmpty(result) || !IsIPv4(result))
24 | {
25 | return "127.0.0.1";
26 | }
27 |
28 | return result;
29 | }
30 |
31 | public bool IsIPv4(string ip)
32 | {
33 | return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
34 | }
35 | }
--------------------------------------------------------------------------------
/Demo/Nancy.Demo2/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的常规信息通过下列特性集
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("Nancy.Demo2")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("Nancy.Demo2")]
13 | [assembly: AssemblyCopyright("版权所有(C) 2015")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 会使此程序集中的类型
18 | // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的某个类型,
19 | // 请针对该类型将 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("55b519eb-63ab-42fc-b5fb-04ec62dce486")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 内部版本号
30 | // 修订号
31 | //
32 | // 可以指定所有这些值,也可以使用“修订号”和“内部版本号”的默认值,
33 | // 方法是按如下所示使用“*”:
34 | [assembly: AssemblyVersion("1.0.0.0")]
35 | [assembly: AssemblyFileVersion("1.0.0.0")]
36 |
--------------------------------------------------------------------------------
/Demo/AspTest/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的一般信息由以下
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("AspTest")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Microsoft")]
12 | [assembly: AssemblyProduct("AspTest")]
13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | //将 ComVisible 设置为 false 将使此程序集中的类型
18 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
19 | //请将此类型的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("83c619a2-4ae4-4029-945b-657f7159396e")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”: :
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Demo/Nancy.Demo2/RazorConfig.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using Nancy.ViewEngines.Razor;
4 |
5 | namespace Nancy.Demo2
6 | {
7 |
8 |
9 | ///
10 | /// Razor配置,如果你需要使用 cshtml,这个配置比较重要,当然,也可以在这儿加入其它的类
11 | ///
12 | public class RazorConfig : IRazorConfiguration
13 | {
14 |
15 | ///
16 | /// 需加载的程序集列表
17 | ///
18 | ///
19 | public IEnumerable GetAssemblyNames()
20 | {
21 | //加了这句,才能处理 cshtml
22 | yield return "System.Web.Razor";
23 | }
24 |
25 | ///
26 | /// 需要添加到cshtml中的名字空间
27 | ///
28 | ///
29 | public IEnumerable GetDefaultNamespaces()
30 | {
31 | yield return "System.Web.Razor";
32 | }
33 |
34 | ///
35 | /// 是否自动引用model名字空间
36 | ///
37 | public bool AutoIncludeModelNamespace
38 | {
39 | get { return true; }
40 | }
41 | }
42 |
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/OwinDog/OwinEngine/OwinAdapterManage.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Service;
3 |
4 | namespace OwinEngine
5 | {
6 |
7 | public sealed class OwinAdapterManage
8 | {
9 | private static readonly OwinManager _owinManager = new OwinManager(OnOwinCallCompleteCallback);
10 |
11 | public bool Process(RequestData requestData)
12 | {
13 | return _owinManager != null && _owinManager.Process(requestData);
14 | }
15 |
16 | ///
17 | /// 如果Connection Close掉了 关闭tcp 否则保持Tcp socket长连接
18 | ///
19 | ///
20 | ///
21 | private static void OnOwinCallCompleteCallback(RequestData req, bool iskeep)
22 | {
23 | if (!iskeep || !req.IsKeepAlive())//Connection 是否Close掉了
24 | {
25 | req.Socket.Dispose();
26 | req.SaveToPoll();
27 | return;
28 | }
29 | OwinHttpWorkerManage.Start((OwinSocket)req.Socket, req._preLoadedBody);
30 | req.SaveToPoll();
31 | }
32 |
33 |
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/Demo/WebSocket.Demo2/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的常规信息通过以下
6 | // 特性集控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("WebSocket.Demo2")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("WebSocket.Demo2")]
13 | [assembly: AssemblyCopyright("Copyright © 2015")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 使此程序集中的类型
18 | // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
19 | // 则将该类型上的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("a0ae50ad-793e-408e-9144-c08a016b04d6")]
24 |
25 | // 程序集的版本信息由下面四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Owin.WebSocket/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的一般信息由以下
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("Owin.WebSocket")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Microsoft")]
12 | [assembly: AssemblyProduct("Owin.WebSocket")]
13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | //将 ComVisible 设置为 false 将使此程序集中的类型
18 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
19 | //请将此类型的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("ed2ee07f-39ca-4f87-9346-e47ed3b5f4e0")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”: :
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Demo/Nancy.Demo2/Web.Debug.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
17 |
18 |
30 |
31 |
--------------------------------------------------------------------------------
/Demo/Nancy.Demo2/Web.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/Demo/Nancy.Demo2/MainModule.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Nancy;
3 |
4 |
5 |
6 | namespace Nancy.Demo2
7 | {
8 |
9 | public class MainModule : NancyModule
10 | {
11 |
12 | ///
13 | /// 构造函数
14 | ///
15 | public MainModule()
16 | {
17 |
18 | //在构造函数中进行路由配置
19 |
20 | Get["/"] = IndexPage;
21 | Get["/test/{abc}"] = ToTest;
22 | Get["/test"] = _ => "this test.....";
23 | Get["/get"] = _ => Request.Session["kkkk"] == null ? "nonoono" : "okokok";
24 | Get["/set"] = _ => { Request.Session["kkkk"] = "okkkk"; return "set ok."; };
25 |
26 | }
27 |
28 |
29 |
30 | ///
31 | /// 主页的实现方法
32 | ///
33 | ///
34 | ///
35 | private dynamic IndexPage(dynamic d)
36 | {
37 | //显示cshtml页
38 | return View["Home/Index"];
39 | }
40 |
41 |
42 |
43 |
44 |
45 | private dynamic ToTest(dynamic d)
46 | {
47 | return View["Test", d];
48 | }
49 |
50 |
51 |
52 | }
53 |
54 |
55 |
56 |
57 |
58 | }
--------------------------------------------------------------------------------
/Demo/Nancy.Demo2/Web.Release.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
17 |
18 |
19 |
31 |
32 |
--------------------------------------------------------------------------------
/OwinDog/Service/CustomeAsyncResult.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Runtime.CompilerServices;
4 | using System.Threading;
5 |
6 | namespace Service
7 | {
8 |
9 |
10 |
11 | public sealed class CustomeAsyncResult : IAsyncResult
12 | {
13 | public CustomeAsyncResult(object obj)
14 | {
15 | AsyncState = obj;
16 | AsyncWaitHandle = new AutoResetEvent(false);
17 | }
18 |
19 |
20 | public byte[] RecvBuffer { get; set; }
21 |
22 |
23 | public int RecvLength { get; set; }
24 |
25 |
26 |
27 | public int RecvOffset { get; set; }
28 |
29 | public object AsyncState { get; set; }
30 |
31 | public AsyncCallback UserCallbackFunc { get; set; }
32 |
33 |
34 | public WaitHandle AsyncWaitHandle { get; set; }
35 |
36 | public int RealRecvSize { get; set; }
37 |
38 |
39 | public bool IsCompleted { get; set; }
40 |
41 |
42 | internal bool SocketIsErrOrClose { get; set; }
43 |
44 |
45 |
46 | internal bool SocketIsTimeOut{ get; set; }
47 |
48 | public bool CompletedSynchronously {
49 | get { return false; }
50 | }
51 |
52 |
53 |
54 |
55 | }
56 |
57 |
58 | }
59 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |  
2 | [](https://www.microsoft.com/net/core)
3 | [](http://www.cnblogs.com/yudongdong)
4 | [](https://github.com/yuzd/OwinDog/stargazers)
5 |
6 |
7 | # 什么是 OWIN ?
8 | .OWIN 的全称是 "Open Web Interface for .NET", OWIN 在 .NET Web 服务器和 .NET Web 应用之间定义了一套标准的接口,
9 | 其目的是为了实现服务器与应用之间的解耦, 鼓励为 .NET Web 应用开发简单模块。
10 |
11 |
12 | # OwinDog 是一款支持OWIN标准的WEB应用的高性能的HTTP服务器,有如下特点:
13 |
14 | 1,跨平台:支持windows、linux等常用操作系统(后者由mono支持);
15 |
16 | 2,超轻量:功能单一而明确:除了静态文件由自身处理外,其它的应用逻辑直接交给用户处理;
17 |
18 | 3,高性能:底层基于 libuv 开发,是完全的异步、非阻塞、事件驱动模型,上层代码也经过了高度优化;libuv是NodeJs的基础库,libuv 是一个高性能事件驱动的程序库,封装了 Windows 和 Unix 平台一些底层特性,为开发者提供了统一的 API,libuv 采用了异步 (asynchronous), 事件驱动 (event-driven)的编程风格, 其主要任务是为开人员提供了一套事件循环和基于I/O(或其他活动)通知的回调函数, libuv 提供了一套核心的工具集, 例如定时器, 非阻塞网络编程的支持, 异步访问文件系统, 子进程以及其他功能,关于libuv的更多内容推荐参考电子书 http://www.nowx.org/uvbook/ 。
19 |
20 |
21 | # 测试访问aspx的demo
22 | [aspx demo](https://files.cnblogs.com/files/yudongdong/%E6%B5%8B%E8%AF%95aspx.zip)
23 |
24 |
25 | 欢迎测试,如果你有什么问题,请提交Issue或者加入QQ群433685124
26 |
--------------------------------------------------------------------------------
/OwinDog/Model/LoopHandle.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Threading;
3 |
4 | namespace Model
5 | {
6 |
7 | public class LoopHandle : HandleBase
8 | {
9 | public void Stop()
10 | {
11 | LibUv.Stop(this);
12 | }
13 |
14 | ///
15 | /// 把监视器和loop联系起来
16 | ///
17 | ///
18 | public void Init(LibUv libUv)
19 | {
20 | base.Init(libUv, libUv.GetUvLoopSize(), Thread.CurrentThread.ManagedThreadId);
21 | LibUv.Init(this);//loop init
22 | }
23 |
24 |
25 | public int Start(int num = 0/*UV_RUN_DEFAULT*/)
26 | {
27 | return LibUv.Run(this, num);
28 | }
29 |
30 | protected override unsafe bool ReleaseHandle()
31 | {
32 | IntPtr ptr = handle;
33 | if (ptr != IntPtr.Zero)
34 | {
35 | IntPtr intPtr = *(IntPtr*)((void*)ptr);
36 | try
37 | {
38 | LibUv.LoopClose(this);
39 | }
40 | catch
41 | {
42 | //ignore
43 | }
44 | handle = IntPtr.Zero;
45 | FreeHandle(ptr, intPtr);
46 | }
47 | return true;
48 | }
49 |
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/Demo/Nancy.Demo2/SiteRootPath.cs:
--------------------------------------------------------------------------------
1 | /******************************************************************
2 | * 为NancyFx提供应用程序根目录绝对路径的类
3 | * ---------------------------------------------------------------
4 | * 要点:类名可以随便取,但必需继续自 IRootPathProvider
5 | * 整个应用程序(网站)只能有一个这样的类
6 | * ****************************************************************/
7 |
8 |
9 | #region
10 |
11 | using System;
12 | using Nancy;
13 | using System.IO;
14 |
15 | #endregion
16 |
17 |
18 | namespace Nancy.Demo2
19 | {
20 |
21 | ///
22 | /// 提供网站物理路径的类
23 | ///
24 | public class SiteRootPath : IRootPathProvider
25 | {
26 |
27 | /**************************************************************
28 | * owindog Owin Server 默认情况下
29 | * 网站是放在 owindog 进程所在文件夹下的site/wwwroot中的
30 | * ----------------------------------------------------------
31 | * 如果你把 NancyFx 的 Views 页放在其它的地方,应该作相应修改
32 | *******************************************************************/
33 |
34 | ///
35 | /// 网站根文件夹物理路径(for owindog)
36 | ///
37 | static readonly string _RootPath = AppDomain.CurrentDomain.GetData(".appPath").ToString();
38 |
39 |
40 | ///
41 | /// 获取网站或WEB应用的根文件夹的物理路径
42 | ///
43 | ///
44 | public string GetRootPath()
45 | {
46 | return _RootPath;
47 |
48 | }
49 |
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/Dog/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("Dog")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("Dog")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("3b51c35f-ef88-493a-8183-4cfeca20f263")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Owin.AspEngine/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("Owin.AspEngine")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("OwinDog")]
12 | [assembly: AssemblyProduct("Owin.AspEngine")]
13 | [assembly: AssemblyCopyright("Copyright ©nainaigu 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("e044c158-1347-4a46-bb69-fe7403d2eb0e")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/OwinDog/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("OwinDog")]
9 | [assembly: AssemblyDescription("www.OwinDog.com")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("OwinDog")]
12 | [assembly: AssemblyProduct("OwinDog")]
13 | [assembly: AssemblyCopyright("Copyright ©nainaigu 2016")]
14 | [assembly: AssemblyTrademark("OwinDog")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("38fd2383-56a2-408d-8cbf-1e175f8d6488")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0")]
37 |
--------------------------------------------------------------------------------
/OwinDog/Service/RequestDataFactory.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 |
5 | namespace Service
6 | {
7 | ///
8 | /// 循环利用
9 | ///
10 | internal static class RequestDataFactory
11 | {
12 | private const int MaxSize = 10000;
13 |
14 | private static readonly Queue AQueue = new Queue(MaxSize);
15 |
16 | ///
17 | /// 获取
18 | ///
19 | ///
20 | public static byte[] Create()
21 | {
22 | byte[] result;
23 | lock (AQueue)
24 | {
25 | if (AQueue.Count < 1)
26 | {
27 | //TcpClient.ReceiveBufferSize Property The size of the receive buffer, in bytes. The default value is 8192 bytes.
28 | result = new byte[8192];
29 | }
30 | else
31 | {
32 | result = AQueue.Dequeue();
33 | }
34 | }
35 | return result;
36 | }
37 |
38 | ///
39 | /// 回收
40 | ///
41 | ///
42 | public static void Recover(byte[] array)
43 | {
44 | if (array == null || array.Length != 8192 || AQueue.Count > MaxSize)
45 | {
46 | return;
47 | }
48 | lock (AQueue)
49 | {
50 | AQueue.Enqueue(array);
51 | }
52 | }
53 |
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/OwinDog/OwinEngine/ISocket.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Net.Sockets;
5 | using System.Runtime.CompilerServices;
6 | using System.Text;
7 |
8 | namespace OwinEngine
9 | {
10 |
11 | public interface ISocket
12 | {
13 | ///
14 | /// 获取访问者IP地址
15 | ///
16 | ///
17 | string GetRemoteIpAddress();
18 |
19 | ///
20 | /// 获取访问者的Ip端口
21 | ///
22 | ///
23 | int GetRemoteIpPort();
24 |
25 | ///
26 | /// 获取本地的IP地址
27 | ///
28 | ///
29 | string LocalIpAddress();
30 |
31 | ///
32 | /// 获取本地的IP端口
33 | ///
34 | ///
35 | int LocalIpPort();
36 |
37 | ///
38 | /// 写操作
39 | ///
40 | ///
41 | ///
42 | void Read(Action callBack, object state);
43 |
44 | ///
45 | /// 读操作
46 | ///
47 | ///
48 | ///
49 | ///
50 | void Write(byte[] array, Action callback, object otherState);
51 |
52 | void WriteForPost(byte[] headDomain, byte[] body, Action callback, object otherState);
53 |
54 | void Dispose();
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/OwinDog/Model/ListenHandle.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Net;
3 |
4 | namespace Model
5 | {
6 |
7 | ///
8 | /// lib uv 的 tcp handle
9 | ///
10 | public class ListenHandle : UvStreamHandle
11 | {
12 | public LoopHandle Loop { get; set; }
13 |
14 |
15 |
16 | public void TcpBind(IPEndPoint iPEndPoint)
17 | {
18 | string text = iPEndPoint.Address.ToString();
19 | LibUv.Addr addr;
20 | Exception ex;
21 | LibUv.Ip4Address(text, iPEndPoint.Port, out addr, out ex);
22 | if (ex != null)
23 | {
24 | Exception ex2;
25 | LibUv.Ip6Address(text, iPEndPoint.Port, out addr, out ex2);
26 | if (ex2 != null)
27 | {
28 | throw ex;
29 | }
30 | }
31 | LibUv.TcpBind(this, ref addr, 0);
32 | }
33 |
34 | public void TcpNodealy(bool flag)
35 | {
36 | LibUv.TcpNodealy(this, flag);
37 | }
38 |
39 | public void Init(LoopHandle loopHandle, Action, object> asyncSendUserPostAction)
40 | {
41 | base.Init(loopHandle.LibUv, loopHandle.LibUv.TcpHandleSize, loopHandle.LoopRunThreadId);
42 | LibUv.TcpInit(loopHandle, this);
43 | Loop=loopHandle;
44 | _postAsync = asyncSendUserPostAction;
45 | }
46 |
47 | public void TcpBind(string ipString, int port)
48 | {
49 | IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse(ipString), port);
50 | TcpBind(iPEndPoint);
51 | }
52 |
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/Owin.AspEngine/AspEngine/AspRequestData.cs:
--------------------------------------------------------------------------------
1 | namespace Owin.AspEngine
2 | {
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Runtime.CompilerServices;
6 |
7 | [Serializable]
8 | internal class AspRequestData
9 | {
10 | public AspRequestData(int reqid, IDictionary env)
11 | {
12 | this.RequestId = reqid;
13 | this.RequestHttpHeader = env["owin.RequestHeaders"] as IDictionary;
14 | this.QueryString = env["owin.RequestQueryString"] as string;
15 | this.Verb = env["owin.RequestMethod"] as string;
16 | this.Protocol = env["owin.RequestProtocol"] as string;
17 | this.UrlPath = env["owin.RequestPath"] as string;
18 | this.RemoteAddress = env["server.RemoteIpAddress"] as string;
19 | this.RemotePort = int.Parse((string) env["server.RemotePort"]);
20 | this.LocalAddress = env["server.LocalIpAddress"] as string;
21 | this.LocalPort = int.Parse((string) env["server.LocalPort"]);
22 | }
23 |
24 | public string LocalAddress { get; private set; }
25 |
26 | public int LocalPort { get; private set; }
27 |
28 | public string Protocol { get; private set; }
29 |
30 | public string QueryString { get; private set; }
31 |
32 | public string RemoteAddress { get; private set; }
33 |
34 | public int RemotePort { get; private set; }
35 |
36 | ///
37 | /// 请求头
38 | ///
39 | public IDictionary RequestHttpHeader { get; private set; }
40 |
41 | public int RequestId { get; private set; }
42 |
43 | public string UrlPath { get; private set; }
44 |
45 | public string Verb { get; private set; }
46 | }
47 | }
48 |
49 |
--------------------------------------------------------------------------------
/OwinDog/Model/AsyncHandle.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.InteropServices;
3 |
4 | namespace Model
5 | {
6 | ///
7 | /// uv_async is the only thread-safe facility that libuv has.
8 | ///
9 | public class AsyncHandle : HandleBase
10 | {
11 | private static readonly LibUv.AsyncInit_callback _uv_async_cb = AsyncCb;
12 |
13 | private Action _callback;
14 |
15 | ///
16 | /// uv_asyncがやってくれるのは、async_cbを呼ぶことだけなので、
17 | /// なにかデータを渡したいときは別途、
18 | /// pthread_mutexなどを使用して共有データをわたすように自分でよしなにやるかんじですね
19 | ///
20 | public void AsyncSend()
21 | {
22 | LibUv.AsyncSend(this);
23 | }
24 |
25 | public void dispose()
26 | {
27 | Dispose();
28 | ReleaseHandle();
29 | }
30 |
31 | private static unsafe void AsyncCb(IntPtr ptrUvAsyncHandle)
32 | {
33 | AsyncHandle asyncHandlea = (AsyncHandle)GCHandle.FromIntPtr(*(IntPtr*)((void*)ptrUvAsyncHandle)).Target;
34 | if (asyncHandlea == null)
35 | {
36 | return;
37 | }
38 | try
39 | {
40 | asyncHandlea._callback();
41 | }
42 | catch
43 | {
44 | //ignore
45 | }
46 | }
47 |
48 | ///
49 | /// 为loop注册了一个异步消息监听器 其他线程就可以通过async监视器给主线程发送消息
50 | ///
51 | ///
52 | ///
53 | public void Init(LoopHandle loopHandle, Action cb)
54 | {
55 | base.Init(loopHandle.LibUv, loopHandle.LibUv.HandSize(LibUv.HandleType.UV_ASYNC), loopHandle.LoopRunThreadId);
56 | _callback = cb;
57 | LibUv.AsyncInit(loopHandle, this, _uv_async_cb);
58 | }
59 |
60 |
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/OwinDog/Model/UvPipeStream.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Model
4 | {
5 |
6 | public class UvPipeStream : HandleBase
7 | {
8 | private static readonly LibUv.PipeConnect_Callback _uv_shutdown_cb = UvShutdownCb;
9 |
10 | private Action _callback;
11 |
12 | private object _state;
13 | public void Init(LoopHandle loopHandle)
14 | {
15 | base.Init(loopHandle.LibUv, loopHandle.LibUv.ConnectReqSize, loopHandle.LoopRunThreadId);
16 | }
17 |
18 |
19 | public void PipeConnect(UvPipeHandle uvPipeHandle, string text, Action callback, object state)
20 | {
21 | _callback = callback;
22 | _state = state;
23 | Alloc();
24 | LibUv.PipeConnect(this, uvPipeHandle, text, _uv_shutdown_cb);
25 | }
26 |
27 | protected override bool ReleaseHandle()
28 | {
29 | _Close_Callback(handle);
30 | handle = IntPtr.Zero;
31 | return true;
32 | }
33 | private static void UvShutdownCb(IntPtr ptrReq, int status)
34 | {
35 | UvPipeStream uvPipeStream = GetObjectFromHandel(ptrReq);
36 | uvPipeStream.DoDispose();
37 |
38 | Exception arg = null;
39 | if (status < 0)
40 | {
41 | uvPipeStream.LibUv.GetException(status, out arg);
42 | }
43 | try
44 | {
45 | uvPipeStream._callback(uvPipeStream, status, arg, uvPipeStream._state);
46 | }
47 | catch (Exception ex)
48 | {
49 | throw ex;
50 | }
51 | finally
52 | {
53 | uvPipeStream._callback = null;
54 | uvPipeStream._state = null;
55 | }
56 | }
57 |
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/Owin.WebSocket/WebSocketConnectionMiddleware.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Text.RegularExpressions;
3 | using System.Threading.Tasks;
4 | using Microsoft.Owin;
5 | using Microsoft.Practices.ServiceLocation;
6 | using System;
7 |
8 | namespace Owin.WebSocket
9 | {
10 | public class WebSocketConnectionMiddleware : OwinMiddleware where T : WebSocketConnection
11 | {
12 | private readonly Regex mMatchPattern;
13 | private readonly IServiceLocator mServiceLocator;
14 |
15 | public WebSocketConnectionMiddleware(OwinMiddleware next, IServiceLocator locator)
16 | : base(next)
17 | {
18 | mServiceLocator = locator;
19 | }
20 |
21 | public WebSocketConnectionMiddleware(OwinMiddleware next, IServiceLocator locator, Regex matchPattern)
22 | : this(next, locator)
23 | {
24 | mMatchPattern = matchPattern;
25 | }
26 |
27 | public override Task Invoke(IOwinContext context)
28 | {
29 | var matches = new Dictionary();
30 |
31 | if (mMatchPattern != null)
32 | {
33 | var match = mMatchPattern.Match(context.Request.Path.Value);
34 | if(!match.Success)
35 | return Next.Invoke(context);
36 |
37 | for (var i = 1; i <= match.Groups.Count; i++)
38 | {
39 | var name = mMatchPattern.GroupNameFromNumber(i);
40 | var value = match.Groups[i];
41 | matches.Add(name, value.Value);
42 | }
43 | }
44 |
45 | T socketConnection;
46 | if(mServiceLocator == null)
47 | socketConnection = Activator.CreateInstance();
48 | else
49 | socketConnection = mServiceLocator.GetInstance();
50 |
51 | return socketConnection.AcceptSocketAsync(context, matches);
52 | }
53 | }
54 | }
--------------------------------------------------------------------------------
/OwinDog/Model/ShutdownHandle.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Model
4 | {
5 | public class ShutdownHandle : HandleBase
6 | {
7 |
8 | private static readonly LibUv.ShutDown_Callback _ShutDown_Callback = new LibUv.ShutDown_Callback(ShutDown_Callback);
9 |
10 | private Action _callBack;
11 |
12 | private object _state;
13 |
14 | public void Init(LoopHandle loopHandle)
15 | {
16 | base.Init(loopHandle.LibUv, loopHandle.LibUv.ShutdownReqSize, loopHandle.LoopRunThreadId);
17 | }
18 |
19 | public void ShutDown(UvStreamHandle uvStreamHandle, Action callBack, object state)
20 | {
21 |
22 | _callBack = callBack;
23 | _state = state;
24 | Alloc();
25 | try
26 | {
27 | LibUv.ShutDown(this, uvStreamHandle, _ShutDown_Callback);
28 | }
29 | catch (Exception ex)
30 | {
31 | DoDispose();
32 | throw ex;
33 | }
34 | }
35 |
36 | private static void ShutDown_Callback(IntPtr intPtr, int arg)
37 | {
38 | ShutdownHandle shutdownHandle = GetObjectFromHandel(intPtr);
39 | if (shutdownHandle == null || shutdownHandle._callBack == null)
40 | {
41 | return;
42 | }
43 | try
44 | {
45 | shutdownHandle._callBack(arg, shutdownHandle._state);
46 | }
47 | catch
48 | {
49 | //ignore
50 | }
51 | shutdownHandle.DoDispose();
52 | shutdownHandle.Dispose();
53 | shutdownHandle._callBack = null;
54 | shutdownHandle._state = null;
55 | }
56 |
57 | protected override bool ReleaseHandle()
58 | {
59 | _Close_Callback(handle);
60 | handle = IntPtr.Zero;
61 | return true;
62 | }
63 |
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/Demo/WebSocket.Demo2/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | WebSocket Test
7 |
8 |
9 |
44 |
45 |
46 |
47 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
你输入什么,服务器就回复什么,试试!!
60 |
61 |
62 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
--------------------------------------------------------------------------------
/OwinDog/Service/RequestCheck.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Concurrent;
3 |
4 | namespace Service
5 | {
6 |
7 | public static class RequestCheck
8 | {
9 | private static string[] NotSafeArray = new string[]
10 | {
11 | "/bin",
12 | "/views",
13 | "/app_code",
14 | "/app_data"
15 | };
16 |
17 | private static readonly ConcurrentDictionary SafeRequestUrlDic = new ConcurrentDictionary();
18 |
19 | ///
20 | /// 测试非法地址
21 | ///
22 | ///
23 | ///
24 | public static bool IsNotSafeRequest(string url)
25 | {
26 | if (string.IsNullOrEmpty(url))
27 | {
28 | return false;
29 | }
30 | bool flag = false;
31 | if (SafeRequestUrlDic.TryGetValue(url, out flag))
32 | {
33 | return flag;
34 | }
35 | flag = true;
36 | int num = url.IndexOf('/', 1);
37 | if (num < 3)
38 | {
39 | return true;
40 | }
41 | string path = url.Substring(0, num);
42 | for (int i = 0; i < NotSafeArray.Length; i++)
43 | {
44 | string item = NotSafeArray[i];
45 | if (string.Equals(path, item, StringComparison.OrdinalIgnoreCase))
46 | {
47 | flag = false;
48 | break;
49 | }
50 | }
51 | if (flag && url.IndexOf("/.") != -1)
52 | {
53 | flag = false;
54 | }
55 | if (flag && url.EndsWith(".config", StringComparison.OrdinalIgnoreCase))
56 | {
57 | flag = false;
58 | }
59 | if (flag && url.EndsWith(".asax", StringComparison.OrdinalIgnoreCase))
60 | {
61 | flag = false;
62 | }
63 | SafeRequestUrlDic[url] = flag;
64 | return flag;
65 | }
66 |
67 | ///
68 | /// 排除
69 | ///
70 | ///
71 | public static void Expect(string key)
72 | {
73 | SafeRequestUrlDic[key] = false;
74 | }
75 |
76 |
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/OwinDog/Service/ApplicationInfo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Threading;
7 | using Util;
8 | using OwinEngine;
9 |
10 | namespace Service
11 | {
12 | public static class ApplicationInfo
13 | {
14 | public const string ServerInfo = "OwinDog/1.0";
15 |
16 | public static readonly string Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
17 |
18 | public static string AppPtah { get; set; }
19 |
20 | ///
21 | /// 默认是 owindog.exe 所在的 site\wwwroot 目录 放置网站运行程序的
22 | ///
23 | public static string Wwwroot { get; set; }
24 |
25 | public static string Approot { get; set; }
26 |
27 | public static OwinAdapter OwinAdapter { get; set; }
28 |
29 |
30 | public static void SetApplicationPath(string appPath, string rootPath)
31 | {
32 | // -root 网站或webapi的物理路径,如 owindog -root d:\myapi\wwwroot。
33 | //(不加该参数时,默认路径是owindog.exe所在文件夹内的site\wwwroot目录)
34 | AppPtah = (appPath);
35 | bool isWindows = SystemUtil.IsWindowOs();
36 | if (string.IsNullOrEmpty(rootPath))
37 | {
38 | Wwwroot = (Path.Combine(appPath, "site", "wwwroot"));
39 | Approot = (Path.Combine(appPath, "site", "approot"));
40 | return;
41 | }
42 | if ((!isWindows && rootPath[0] != '/') || (isWindows && rootPath.Length > 1 && rootPath[1] != ':'))
43 | {
44 | string root = Path.Combine(AppPtah, rootPath);
45 | root = Path.GetFullPath(root);
46 | Wwwroot = (root);
47 | DirectoryInfo directoryInfo = new DirectoryInfo(Wwwroot);
48 | string fullName = directoryInfo.Parent.FullName;
49 | root = Path.Combine(fullName, "approot");
50 | if (Directory.Exists(root))
51 | {
52 | Approot = (root);
53 | }
54 | }
55 | else
56 | {
57 | Wwwroot = rootPath;
58 | string fullName;
59 | try
60 | {
61 | fullName = new DirectoryInfo(rootPath).Parent.FullName;
62 | }
63 | catch
64 | {
65 | throw new IOException(string.Format("Error. Path: {0}", rootPath));
66 | }
67 |
68 | string root = Path.Combine(fullName, "approot");
69 | if (Directory.Exists(root))
70 | {
71 | Approot = root;
72 | }
73 | }
74 | }
75 |
76 |
77 |
78 | }
79 |
80 |
81 |
82 | }
83 |
84 |
--------------------------------------------------------------------------------
/Demo/WebSocket.Demo2/WebSocket.Demo2.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {DA9B5E13-8607-4E44-8350-74A011D5D07A}
8 | Library
9 | Properties
10 | WebSocket.Demo2
11 | WebSocket.Demo2
12 | v4.5
13 | 512
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | AnyCPU
27 | pdbonly
28 | true
29 | bin\Release\
30 | TRACE
31 | prompt
32 | 4
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
62 |
--------------------------------------------------------------------------------
/Owin.WebSocket/Handlers/NetWebSocket.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Net.WebSockets;
3 | using System.Threading;
4 | using System.Threading.Tasks;
5 | using Owin.WebSocket.Extensions;
6 |
7 | namespace Owin.WebSocket.Handlers
8 | {
9 | class NetWebSocket: IWebSocket
10 | {
11 | private readonly TaskQueue mSendQueue;
12 | private readonly System.Net.WebSockets.WebSocket mWebSocket;
13 |
14 | public NetWebSocket(System.Net.WebSockets.WebSocket webSocket)
15 | {
16 | mWebSocket = webSocket;
17 | mSendQueue = new TaskQueue();
18 | }
19 |
20 | public TaskQueue SendQueue
21 | {
22 | get { return mSendQueue; }
23 | }
24 |
25 | public WebSocketCloseStatus? CloseStatus
26 | {
27 | get { return mWebSocket.CloseStatus; }
28 | }
29 |
30 | public string CloseStatusDescription
31 | {
32 | get { return mWebSocket.CloseStatusDescription; }
33 | }
34 |
35 | public Task SendText(ArraySegment data, bool endOfMessage, CancellationToken cancelToken)
36 | {
37 | return Send(data, WebSocketMessageType.Text, endOfMessage, cancelToken);
38 | }
39 |
40 | public Task SendBinary(ArraySegment data, bool endOfMessage, CancellationToken cancelToken)
41 | {
42 | return Send(data, WebSocketMessageType.Binary, endOfMessage, cancelToken);
43 | }
44 |
45 | public Task Send(ArraySegment data, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancelToken)
46 | {
47 | var sendContext = new SendContext(data, endOfMessage, messageType, cancelToken);
48 |
49 | return mSendQueue.Enqueue(
50 | async s =>
51 | {
52 | await mWebSocket.SendAsync(s.Buffer, s.Type, s.EndOfMessage, s.CancelToken);
53 | },
54 | sendContext);
55 | }
56 |
57 | public Task Close(WebSocketCloseStatus closeStatus, string closeDescription, CancellationToken cancelToken)
58 | {
59 | return mWebSocket.CloseAsync(closeStatus, closeDescription, cancelToken);
60 | }
61 |
62 | public async Task, WebSocketMessageType>> ReceiveMessage(byte[] buffer, CancellationToken cancelToken)
63 | {
64 | var count = 0;
65 | WebSocketReceiveResult result;
66 | do
67 | {
68 | var segment = new ArraySegment(buffer, count, buffer.Length - count);
69 | result = await mWebSocket.ReceiveAsync(segment, cancelToken);
70 |
71 | count += result.Count;
72 | }
73 | while (!result.EndOfMessage);
74 |
75 | return new Tuple, WebSocketMessageType>(new ArraySegment(buffer, 0, count), result.MessageType);
76 | }
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/Dog/Dog.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {3B51C35F-EF88-493A-8183-4CFECA20F263}
8 | Exe
9 | Properties
10 | Dog
11 | Dog
12 | v4.5
13 | 512
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | AnyCPU
27 | pdbonly
28 | true
29 | bin\Release\
30 | TRACE
31 | prompt
32 | 4
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 | {38fd2383-56a2-408d-8cbf-1e175f8d6488}
54 | OwinDog
55 |
56 |
57 |
58 |
65 |
--------------------------------------------------------------------------------
/Owin.AspEngine/AspEngine/AspRequestBroker.cs:
--------------------------------------------------------------------------------
1 | namespace Owin.AspEngine
2 | {
3 | using System;
4 | using System.Runtime.CompilerServices;
5 |
6 | internal class AspRequestBroker : MarshalByRefObject
7 | {
8 | private DelegateDomainUnload _domainUnlocad;
9 | private DelegateRead _read;
10 | private DelegateRequestEnd _requestEnd;
11 | private DelegateWrite _write;
12 | private DelegateWriteHeader _writeHeader;
13 | private DelegateWriteHttpStatus _writeStatus;
14 |
15 | public AspRequestBroker(DelegateRead read, DelegateWrite write, DelegateWriteHeader writeHeader, DelegateWriteHttpStatus writeStatus, DelegateRequestEnd reqEnd, DelegateDomainUnload domainUnload)
16 | {
17 | this._read = read;
18 | this._write = write;
19 | this._writeHeader = writeHeader;
20 | this._writeStatus = writeStatus;
21 | this._requestEnd = reqEnd;
22 | this._domainUnlocad = domainUnload;
23 | }
24 |
25 | public void DomainUnload()
26 | {
27 | this._domainUnlocad();
28 | }
29 |
30 | public override object InitializeLifetimeService() =>
31 | null;
32 |
33 | public int Read(int id, byte[] buffer, int offset, int size) =>
34 | this._read(id, buffer, offset, size);
35 |
36 | public void RequestEnd(int id, bool keep)
37 | {
38 | this._requestEnd(id, keep);
39 | }
40 |
41 | public void Write(int id, byte[] buffer, int offset, int size)
42 | {
43 | this._write(id, buffer, offset, size);
44 | }
45 |
46 | public void WriteHeader(int id, string name, string value)
47 | {
48 | try
49 | {
50 | this._writeHeader(id, name, value);
51 | }
52 | catch (Exception exception)
53 | {
54 | Console.WriteLine("**** writeHandler: {0}", exception);
55 | throw;
56 | }
57 | }
58 |
59 | public void WriteStatus(int id, int statusCode, string statusDescription)
60 | {
61 | try
62 | {
63 | this._writeStatus(id, statusCode, statusDescription);
64 | }
65 | catch
66 | {
67 | Console.WriteLine("*** write status");
68 | throw;
69 | }
70 | }
71 |
72 | public delegate void DelegateDomainUnload();
73 |
74 | public delegate int DelegateRead(int id, byte[] buffer, int offset, int size);
75 |
76 | public delegate void DelegateRequestEnd(int id, bool keep);
77 |
78 | public delegate void DelegateWrite(int id, byte[] buffer, int offset, int size);
79 |
80 | public delegate void DelegateWriteHeader(int id, string name, string value);
81 |
82 | public delegate void DelegateWriteHttpStatus(int id, int statusCode, string statusDescription);
83 | }
84 | }
85 |
86 |
--------------------------------------------------------------------------------
/Demo/AspTest/AspTest.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {83C619A2-4AE4-4029-945B-657F7159396E}
8 | Library
9 | Properties
10 | AspTest
11 | AspTest
12 | v4.5
13 | 512
14 |
15 |
16 | true
17 | full
18 | false
19 | bin\Debug\
20 | DEBUG;TRACE
21 | prompt
22 | 4
23 |
24 |
25 | pdbonly
26 | true
27 | bin\Release\
28 | TRACE
29 | prompt
30 | 4
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 | Default.aspx
46 |
47 |
48 |
49 |
50 |
51 | {e044c158-1347-4a46-bb69-fe7403d2eb0e}
52 | Owin.AspEngine
53 |
54 |
55 |
56 |
57 |
58 |
59 |
66 |
--------------------------------------------------------------------------------
/Owin.AspEngine/Owin.AspEngine.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {E044C158-1347-4A46-BB69-FE7403D2EB0E}
8 | Library
9 | Properties
10 | Owin.AspEngine
11 | Owin.AspEngine
12 | v4.5
13 | 512
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 | true
25 |
26 |
27 | AnyCPU
28 | pdbonly
29 | true
30 | bin\Release\
31 | TRACE
32 | prompt
33 | 4
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
66 |
--------------------------------------------------------------------------------
/Owin.WebSocket/Extensions/OwinExtension.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Collections.Generic;
4 | using System.Text.RegularExpressions;
5 | using Microsoft.Practices.ServiceLocation;
6 |
7 | namespace Owin.WebSocket.Extensions
8 | {
9 | ///
10 | /// https://github.com/bryceg/Owin.WebSocket
11 | ///
12 | public static class OwinExtension
13 | {
14 | ///
15 | /// Maps a static URI to a web socket consumer
16 | ///
17 | /// Type of WebSocketHubConnection
18 | /// Owin App
19 | /// Static URI to map to the hub
20 | /// Service locator to use for getting instances of T
21 | public static void MapWebSocketRoute(this IAppBuilder app, string route, IServiceLocator serviceLocator = null)
22 | where T : WebSocketConnection
23 | {
24 | app.Map(route, config => config.Use>(serviceLocator));
25 | }
26 |
27 | ///
28 | /// Maps a URI pattern to a web socket consumer using a Regex pattern mach on the URI
29 | ///
30 | /// Type of WebSocketHubConnection
31 | /// Owin app ///
32 | /// Regex pattern of the URI to match. Capture groups will be sent to the hub on the Arguments property
33 | /// Service locator to use for getting instances of T
34 | public static void MapWebSocketPattern(this IAppBuilder app, string regexPatternMatch, IServiceLocator serviceLocator = null)
35 | where T : WebSocketConnection
36 | {
37 | app.Use>(serviceLocator, new Regex(regexPatternMatch, RegexOptions.Compiled | RegexOptions.IgnoreCase));
38 | }
39 |
40 | ///
41 | /// Maps a static URI route to the web socket connection using the WebSocketRouteAttribute
42 | ///
43 | /// Type of WebSocketHubConnection
44 | /// Owin App
45 | /// Service locator to use for getting instances of T
46 | public static void MapWebSocketRoute(this IAppBuilder app, IServiceLocator serviceLocator = null)
47 | where T : WebSocketConnection
48 | {
49 | var routeAttributes = typeof(T).GetCustomAttributes(typeof(WebSocketRouteAttribute), true);
50 |
51 | if (routeAttributes.Length == 0)
52 | throw new InvalidOperationException(typeof(T).Name + " type must have attribute of WebSocketRouteAttribute for mapping");
53 |
54 | foreach (var routeAttribute in routeAttributes.Cast())
55 | {
56 | app.Map(routeAttribute.Route, config => config.Use>(serviceLocator));
57 | }
58 | }
59 |
60 | internal static T Get(this IDictionary dictionary, string key)
61 | {
62 | object item;
63 | if (dictionary.TryGetValue(key, out item))
64 | {
65 | return (T) item;
66 | }
67 |
68 | return default(T);
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/Owin.AspEngine/AspEngine/AspApplicationHost.cs:
--------------------------------------------------------------------------------
1 | namespace Owin.AspEngine
2 | {
3 | using System;
4 | using System.Reflection;
5 | using System.Runtime.CompilerServices;
6 | using System.Text;
7 | using System.Web;
8 | using System.Web.Configuration;
9 |
10 | internal sealed class AspApplicationHost : MarshalByRefObject
11 | {
12 | private string _mPath;
13 | private volatile bool _mUnloading;
14 | private string _mVPath;
15 | private AspRequestBroker _requestBroker;
16 |
17 |
18 | public AspApplicationHost()
19 | {
20 | AppDomain.CurrentDomain.DomainUnload += new EventHandler(this.OnHostDomainUnload);
21 | try
22 | {
23 | this.WebConfigResponseEncoding = this.GetResponseEncodingFromWebConfig();
24 | }
25 | catch
26 | {
27 | this.WebConfigResponseEncoding = Encoding.UTF8;
28 | }
29 | }
30 |
31 | private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) =>
32 | null;
33 |
34 | ///
35 | /// 从Web.config中的配置节点读取ResponseEncoding
36 | ///
37 | ///
38 | private Encoding GetResponseEncodingFromWebConfig()
39 | {
40 | try
41 | {
42 | GlobalizationSection section = WebConfigurationManager.GetSection("system.web/globalization") as GlobalizationSection;
43 | return ((section == null) ? Encoding.UTF8 : section.ResponseEncoding);
44 | }
45 | catch
46 | {
47 | return Encoding.UTF8;
48 | }
49 | }
50 |
51 | public override object InitializeLifetimeService() =>
52 | null;
53 |
54 | ///
55 | /// 要求应用程序域退出时
56 | ///
57 | ///
58 | ///
59 | private void OnHostDomainUnload(object o, EventArgs args)
60 | {
61 | try
62 | {
63 | this._mUnloading = true;
64 | this._requestBroker.DomainUnload();
65 | }
66 | catch
67 | {
68 | }
69 | }
70 |
71 | public void Process(AspRequestData req)
72 | {
73 | new AspRequestWorker().ProcessRequest(req);
74 | }
75 |
76 | public void SetRequestBroker(AspRequestBroker broker)
77 | {
78 | this._requestBroker = broker;
79 | AspRequestWorker.Init(this, broker);
80 | }
81 |
82 | public void UnLoadAppDomain()
83 | {
84 | try
85 | {
86 | this._mUnloading = true;
87 | HttpRuntime.UnloadAppDomain();
88 | }
89 | catch
90 | {
91 | }
92 | }
93 |
94 | internal AppDomain Domain =>
95 | AppDomain.CurrentDomain;
96 |
97 | public string Path =>
98 | (this._mPath ?? (this._mPath = AppDomain.CurrentDomain.GetData(".appPath").ToString()));
99 |
100 | public string VPath =>
101 | (this._mVPath ?? (this._mVPath = AppDomain.CurrentDomain.GetData(".appVPath").ToString()));
102 |
103 | public Encoding WebConfigResponseEncoding { get; private set; }
104 | }
105 | }
106 |
107 |
--------------------------------------------------------------------------------
/Demo/Nancy.Demo2/Adapter.cs:
--------------------------------------------------------------------------------
1 | /**************************************************************************************
2 | * 相对完整的,能支持cshtml文件的nancy应用示例
3 | * -------------------------------------------------------------------------------
4 | * 要点:1,了解如何为AppBuilder添加参数,构造出一个比较完善的适应性强的适配器;
5 | * 2,一个比较完整的可以使用 Razor 开发网站的NancyFx环境的各种必要的配置;
6 | *************************************************************************************/
7 |
8 |
9 |
10 | #region
11 |
12 | using System;
13 | using System.Collections.Generic;
14 | using Microsoft.Owin.Builder;
15 | using System.Threading;
16 | using System.Threading.Tasks;
17 |
18 | #endregion
19 |
20 |
21 |
22 | namespace Nancy.Demo2
23 | {
24 |
25 | ///
26 | /// owin/owindog OWIN适配器
27 | ///
28 | class Adapter
29 | {
30 |
31 |
32 | /*************************************
33 | * 这是一个比较完整的适配器示例
34 | * ***********************************/
35 |
36 |
37 |
38 | ///
39 | /// OWIN 应用程序委托
40 | ///
41 | static Func, Task> _owinApp;
42 |
43 |
44 | ///
45 | /// 适配器构造函数
46 | ///
47 | public Adapter()
48 | {
49 |
50 | //实例化一个应用程序生成器
51 | var builder = new AppBuilder();
52 |
53 |
54 |
55 | // 为生成器添加一些参数
56 | // 因某些OWIN框架需要从该参数中得到一些初始化环境信息
57 | // 这些信息可以包括 如“owin版本”“服务器功”能等等
58 | var properties = builder.Properties;
59 | properties["owin.Version"] = "1.0"; // 只能是1.0
60 |
61 | var disposeSource = new CancellationTokenSource();
62 | properties["server.OnDispose"] = disposeSource.Token;
63 |
64 | Func svrInitCallback = null;
65 | Action> init = (callback) => { svrInitCallback = callback; };
66 | properties["server.OnInit"] = init;
67 | //.......
68 |
69 | var capabilities = properties.ContainsKey("server.Capabilities") ? properties["server.Capabilities"] as IDictionary : new Dictionary();
70 | properties["server.Capabilities"] = capabilities;
71 | capabilities["server.Name"] = "owindog";
72 | //capabilities["websocket.Version"] = "1.0";
73 | //......
74 |
75 |
76 |
77 | //实例化用户的启动类,并调用配置方法
78 | //如果用户启动类在其它的dll中,就需要通过反射找出这个类
79 | var startup = new Startup();
80 | startup.Configuration(builder);
81 |
82 | //构建OWIN应用并获取该应用的代理(委托)方法
83 | _owinApp = builder.Build();
84 |
85 |
86 | //要求应用程序域退出时,向本类发出通知
87 | AppDomain.CurrentDomain.DomainUnload += ((o, e) => { disposeSource.Cancel(); });
88 |
89 | //回调应用层初始化函数
90 | if (svrInitCallback != null) svrInitCallback().Wait();
91 |
92 | }
93 |
94 |
95 |
96 |
97 | ///
98 | /// *** owin/owindog所需要的关键函数 ***
99 | ///
100 | /// 新请求的环境字典,具体内容参见OWIN标准
101 | /// 返回一个正在运行或已经完成的任务
102 | public Task OwinMain(IDictionary env)
103 | {
104 | return _owinApp == null ? null : _owinApp(env);
105 | }
106 |
107 |
108 | } //end class
109 |
110 |
111 | } //end namespace
112 |
--------------------------------------------------------------------------------
/OwinDog/Util/HttpCodeUtil.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Runtime.CompilerServices;
4 | using System.Threading;
5 |
6 | namespace Util
7 | {
8 |
9 | public static class HttpCodeUtil
10 | {
11 | public static string Get(int key)
12 | {
13 | string result;
14 | if (!_dictDescription.TryGetValue(key, out result))
15 | {
16 | result = "OK";
17 | }
18 | return result;
19 | }
20 |
21 | private static readonly IDictionary _dictDescription = new Dictionary
22 | {
23 | {
24 | 100,
25 | "Continue"
26 | },
27 | {
28 | 101,
29 | "Witching Protocols"
30 | },
31 | {
32 | 102,
33 | "Processing"
34 | },
35 | {
36 | 200,
37 | "OK"
38 | },
39 | {
40 | 201,
41 | "Created"
42 | },
43 | {
44 | 202,
45 | "Accepted"
46 | },
47 | {
48 | 203,
49 | "Non-Authoritative Information"
50 | },
51 | {
52 | 204,
53 | "No Content"
54 | },
55 | {
56 | 205,
57 | "Reset Content"
58 | },
59 | {
60 | 206,
61 | "Partial Content"
62 | },
63 | {
64 | 207,
65 | "Multi-Status"
66 | },
67 | {
68 | 300,
69 | "Multiple Choices"
70 | },
71 | {
72 | 301,
73 | "Moved Permanently"
74 | },
75 | {
76 | 302,
77 | "Found"
78 | },
79 | {
80 | 303,
81 | "See Other"
82 | },
83 | {
84 | 304,
85 | "Not Modified"
86 | },
87 | {
88 | 305,
89 | "Use Proxy"
90 | },
91 | {
92 | 306,
93 | "Switch Proxy"
94 | },
95 | {
96 | 307,
97 | "Temporary Redirect"
98 | },
99 | {
100 | 400,
101 | "Bad Request"
102 | },
103 | {
104 | 401,
105 | "Unauthorized"
106 | },
107 | {
108 | 402,
109 | "Payment Required"
110 | },
111 | {
112 | 403,
113 | "Forbidden"
114 | },
115 | {
116 | 404,
117 | "Not Found"
118 | },
119 | {
120 | 405,
121 | "Method Not Allowed"
122 | },
123 | {
124 | 406,
125 | "Not Acceptable"
126 | },
127 | {
128 | 407,
129 | "Proxy Authentication Required"
130 | },
131 | {
132 | 408,
133 | "Request Time-Out"
134 | },
135 | {
136 | 409,
137 | "Conflict"
138 | },
139 | {
140 | 410,
141 | "Gone"
142 | },
143 | {
144 | 411,
145 | "Length Required"
146 | },
147 | {
148 | 412,
149 | "Precondition Failed"
150 | },
151 | {
152 | 413,
153 | "Request Entity Too Large"
154 | },
155 | {
156 | 414,
157 | "Request-URI Too Large"
158 | },
159 | {
160 | 415,
161 | "Unsupported Media Type"
162 | },
163 | {
164 | 416,
165 | "Requested range not satisfiable"
166 | },
167 | {
168 | 417,
169 | "Expectation Failed"
170 | },
171 | {
172 | 500,
173 | "Internal Server Error"
174 | },
175 | {
176 | 501,
177 | "Not Implemented"
178 | },
179 | {
180 | 502,
181 | "Bad Gateway"
182 | },
183 | {
184 | 503,
185 | "Service Unavailable"
186 | },
187 | {
188 | 504,
189 | "Gateway Time-out"
190 | },
191 | {
192 | 505,
193 | "HTTP Version not supported"
194 | },
195 | {
196 | 506,
197 | "Variant Also Negotiates"
198 | },
199 | {
200 | 509,
201 | "Bandwidth Limit Exceeded"
202 | }
203 | };
204 | }
205 |
206 |
207 |
208 |
209 |
210 | }
211 |
--------------------------------------------------------------------------------
/Owin.WebSocket/Extensions/TaskQueue.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Threading;
3 | using System.Threading.Tasks;
4 |
5 | namespace Owin.WebSocket.Extensions
6 | {
7 | // Allows serial queuing of Task instances
8 | // The tasks are not called on the current synchronization context
9 | public sealed class TaskQueue
10 | {
11 | private readonly object mLockObj = new object();
12 | private Task mLastQueuedTask;
13 | private volatile bool mDrained;
14 | private int? mMaxSize;
15 | private int mSize;
16 |
17 | ///
18 | /// Current size of the queue depth
19 | ///
20 | public int Size { get { return mSize; } }
21 |
22 | ///
23 | /// Maximum size of the queue depth. Null = unlimited
24 | ///
25 | public int? MaxSize { get { return mMaxSize; } }
26 |
27 | public TaskQueue()
28 | : this(TaskAsyncHelper.Empty)
29 | {
30 | }
31 |
32 | public TaskQueue(Task initialTask)
33 | {
34 | mLastQueuedTask = initialTask;
35 | }
36 |
37 | ///
38 | /// Set the maximum size of the Task Queue chained operations.
39 | /// When pending send operations limits reached a null Task will be returned from Enqueue
40 | ///
41 | /// Maximum size of the queue
42 | public void SetMaxQueueSize(int? maxSize)
43 | {
44 | mMaxSize = maxSize;
45 | }
46 |
47 | ///
48 | /// Enqueue a new task on the end of the queue
49 | ///
50 | /// The enqueued Task or NULL if the max size of the queue was reached
51 | public Task Enqueue(Func taskFunc, T state)
52 | {
53 | // Lock the object for as short amount of time as possible
54 | lock (mLockObj)
55 | {
56 | if (mDrained)
57 | {
58 | return mLastQueuedTask;
59 | }
60 |
61 | Interlocked.Increment(ref mSize);
62 |
63 | if (mMaxSize != null)
64 | {
65 | // Increment the size if the queue
66 | if (mSize > mMaxSize)
67 | {
68 | Interlocked.Decrement(ref mSize);
69 |
70 | // We failed to enqueue because the size limit was reached
71 | return null;
72 | }
73 | }
74 |
75 | var newTask = mLastQueuedTask.Then((next, nextState) =>
76 | {
77 | return next(nextState).Finally(s =>
78 | {
79 | var queue = (TaskQueue)s;
80 | Interlocked.Decrement(ref queue.mSize);
81 | },
82 | this);
83 | },
84 | taskFunc, state);
85 |
86 | mLastQueuedTask = newTask;
87 | return newTask;
88 | }
89 | }
90 |
91 | ///
92 | /// Triggers a drain fo the task queue and blocks until the drain completes
93 | ///
94 | public void Drain()
95 | {
96 | lock (mLockObj)
97 | {
98 | mDrained = true;
99 |
100 | mLastQueuedTask.Wait();
101 |
102 | mDrained = false;
103 | }
104 | }
105 | }
106 | }
--------------------------------------------------------------------------------
/OwinDog/Service/ActionQueue.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Runtime.CompilerServices;
5 | using System.Threading;
6 | using Util;
7 |
8 | namespace Service
9 | {
10 | ///
11 | /// 每隔指定时间 执行所包含的Action
12 | ///
13 | public static class ActionQueue
14 | {
15 |
16 | private static bool _flag;
17 |
18 | private static readonly List _actionParamList;
19 |
20 | public static DateTime Time { get; set; }
21 |
22 | public static long LongTimes { get; set; }
23 |
24 | static ActionQueue()
25 | {
26 | _flag = false;
27 | _actionParamList = new List();
28 | initDateTimeAndLong();
29 | new Thread(new ThreadStart(Init))
30 | {
31 | IsBackground = true
32 | }.Start();
33 | }
34 |
35 | private static void ExcuteActionParam(object obj)
36 | {
37 | ActionParam actionParam = obj as ActionParam;
38 | try
39 | {
40 | if (actionParam != null) actionParam.Excute();
41 | }
42 | catch
43 | {
44 | //ignore
45 | }
46 | finally
47 | {
48 | if (actionParam != null) actionParam.IsBreak = false;
49 | }
50 | }
51 |
52 | public static void AddAction(Action action, int times)
53 | {
54 | lock (_actionParamList)
55 | {
56 | ActionParam item = new ActionParam
57 | {
58 | Excute = action,
59 | times = times,
60 | longTimes = CommonUtil.CurrentTimes()
61 | };
62 | _actionParamList.Add(item);
63 | }
64 | }
65 |
66 | private static void Init()
67 | {
68 | while (!_flag)
69 | {
70 | initDateTimeAndLong();
71 | Run();
72 | Thread.Sleep(200);
73 | }
74 | _flag = true;
75 | }
76 |
77 | private static void initDateTimeAndLong()
78 | {
79 | Time= DateTime.Now;
80 | LongTimes = CommonUtil.CurrentTimes();//从1970/01/01 00:00:01 到现在经过的毫秒数了
81 | }
82 | private static void Run()
83 | {
84 | if (_actionParamList == null || _actionParamList.Count < 1)
85 | {
86 | return;
87 | }
88 | long num = CommonUtil.CurrentTimes();//当前毫秒数
89 | lock (_actionParamList)
90 | {
91 | foreach (ActionParam current in _actionParamList)
92 | {
93 | if (checked(num - current.times) >= (long)current.longTimes && !current.IsBreak)
94 | {
95 | current.longTimes = num;
96 | current.IsBreak = true;
97 | if (!ThreadPool.UnsafeQueueUserWorkItem(new WaitCallback(ExcuteActionParam), current))
98 | {
99 | current.IsBreak = false;
100 | }
101 | }
102 | }
103 | }
104 | }
105 |
106 |
107 | private class ActionParam
108 | {
109 | public Action Excute;
110 |
111 | public int times;
112 |
113 | public long longTimes;
114 |
115 | public bool IsBreak;
116 | }
117 | }
118 | }
119 |
120 |
--------------------------------------------------------------------------------
/Owin.WebSocket/Owin.WebSocket.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {ED2EE07F-39CA-4F87-9346-E47ED3B5F4E0}
8 | Library
9 | Properties
10 | Owin.WebSocket
11 | Owin.WebSocket
12 | v4.5
13 | 512
14 |
15 |
16 | true
17 | full
18 | false
19 | bin\Debug\
20 | DEBUG;TRACE
21 | prompt
22 | 4
23 |
24 |
25 | pdbonly
26 | true
27 | bin\Release\
28 | TRACE
29 | prompt
30 | 4
31 |
32 |
33 |
34 | ..\packages\Microsoft.Owin.3.1.0\lib\net45\Microsoft.Owin.dll
35 | True
36 |
37 |
38 | ..\packages\CommonServiceLocator.1.3\lib\portable-net4+sl5+netcore45+wpa81+wp8\Microsoft.Practices.ServiceLocation.dll
39 | True
40 |
41 |
42 | ..\packages\Owin.1.0\lib\net40\Owin.dll
43 | True
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
78 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 | .svn/
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | build/
21 | bld/
22 | [Bb]in/
23 | [Oo]bj/
24 |
25 | # Visual Studo 2015 cache/options directory
26 | .vs/
27 |
28 | # MSTest test Results
29 | [Tt]est[Rr]esult*/
30 | [Bb]uild[Ll]og.*
31 |
32 | # NUNIT
33 | *.VisualState.xml
34 | TestResult.xml
35 |
36 | # Build Results of an ATL Project
37 | [Dd]ebugPS/
38 | [Rr]eleasePS/
39 | dlldata.c
40 |
41 | # DNX
42 | project.lock.json
43 | artifacts/
44 |
45 | *_i.c
46 | *_p.c
47 | *_i.h
48 | *.ilk
49 | *.meta
50 | *.obj
51 | *.pch
52 | *.pdb
53 | *.pgc
54 | *.pgd
55 | *.rsp
56 | *.sbr
57 | *.tlb
58 | *.tli
59 | *.tlh
60 | *.tmp
61 | *.tmp_proj
62 | *.log
63 | *.vspscc
64 | *.vssscc
65 | .builds
66 | *.pidb
67 | *.svclog
68 | *.scc
69 |
70 | # Chutzpah Test files
71 | _Chutzpah*
72 |
73 | # Visual C++ cache files
74 | ipch/
75 | *.aps
76 | *.ncb
77 | *.opensdf
78 | *.sdf
79 | *.cachefile
80 |
81 | # Visual Studio profiler
82 | *.psess
83 | *.vsp
84 | *.vspx
85 |
86 | # TFS 2012 Local Workspace
87 | $tf/
88 |
89 | # Guidance Automation Toolkit
90 | *.gpState
91 |
92 | # ReSharper is a .NET coding add-in
93 | _ReSharper*/
94 | *.[Rr]e[Ss]harper
95 | *.DotSettings.user
96 |
97 | # JustCode is a .NET coding add-in
98 | .JustCode
99 |
100 | # TeamCity is a build add-in
101 | _TeamCity*
102 |
103 | # DotCover is a Code Coverage Tool
104 | *.dotCover
105 |
106 | # NCrunch
107 | _NCrunch_*
108 | .*crunch*.local.xml
109 |
110 | # MightyMoose
111 | *.mm.*
112 | AutoTest.Net/
113 |
114 | # Web workbench (sass)
115 | .sass-cache/
116 |
117 | # Installshield output folder
118 | [Ee]xpress/
119 |
120 | # DocProject is a documentation generator add-in
121 | DocProject/buildhelp/
122 | DocProject/Help/*.HxT
123 | DocProject/Help/*.HxC
124 | DocProject/Help/*.hhc
125 | DocProject/Help/*.hhk
126 | DocProject/Help/*.hhp
127 | DocProject/Help/Html2
128 | DocProject/Help/html
129 |
130 | # Click-Once directory
131 | publish/
132 |
133 | # Publish Web Output
134 | *.[Pp]ublish.xml
135 | *.azurePubxml
136 | # TODO: Comment the next line if you want to checkin your web deploy settings
137 | # but database connection strings (with potential passwords) will be unencrypted
138 | *.pubxml
139 | *.publishproj
140 |
141 | # NuGet Packages
142 | *.nupkg
143 | # The packages folder can be ignored because of Package Restore
144 | **/packages/*
145 | # except build/, which is used as an MSBuild target.
146 | !**/packages/build/
147 | # Uncomment if necessary however generally it will be regenerated when needed
148 | #!**/packages/repositories.config
149 |
150 | # Windows Azure Build Output
151 | csx/
152 | *.build.csdef
153 |
154 | # Windows Store app package directory
155 | AppPackages/
156 |
157 | # Visual Studio cache files
158 | # files ending in .cache can be ignored
159 | *.[Cc]ache
160 | # but keep track of directories ending in .cache
161 | !*.[Cc]ache/
162 |
163 | # Others
164 | ClientBin/
165 | [Ss]tyle[Cc]op.*
166 | ~$*
167 | *~
168 | *.dbmdl
169 | *.dbproj.schemaview
170 | *.pfx
171 | *.publishsettings
172 | node_modules/
173 | bower_components/
174 | orleans.codegen.cs
175 |
176 | # RIA/Silverlight projects
177 | Generated_Code/
178 |
179 | # Backup & report files from converting an old project file
180 | # to a newer Visual Studio version. Backup files are not needed,
181 | # because we have git ;-)
182 | _UpgradeReport_Files/
183 | Backup*/
184 | UpgradeLog*.XML
185 | UpgradeLog*.htm
186 |
187 | # SQL Server files
188 | *.mdf
189 | *.ldf
190 |
191 | # Business Intelligence projects
192 | *.rdl.data
193 | *.bim.layout
194 | *.bim_*.settings
195 |
196 | # Microsoft Fakes
197 | FakesAssemblies/
198 |
199 | # Node.js Tools for Visual Studio
200 | .ntvs_analysis.dat
201 |
202 | # Visual Studio 6 build log
203 | *.plg
204 |
205 | # Visual Studio 6 workspace options file
206 | *.opt
207 |
208 | UpLoad/
209 | driver_config.xml
210 |
--------------------------------------------------------------------------------
/OwinDog/OwinEngine/HeaderDictionary.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 |
6 | namespace OwinEngine
7 | {
8 | internal class HeaderDictionary : IDictionary, ICollection>, IEnumerable>, IEnumerable
9 | {
10 | private readonly Dictionary Headers;
11 |
12 | public HeaderDictionary()
13 | {
14 | Headers = new Dictionary(StringComparer.OrdinalIgnoreCase);
15 | }
16 |
17 | public void Add(KeyValuePair item)
18 | {
19 | Headers.Add(item.Key, item.Value);
20 | }
21 |
22 | public void Add(string key, string[] value)
23 | {
24 | Headers.Add(key, value);
25 | }
26 |
27 | public void Clear()
28 | {
29 | Headers.Clear();
30 | }
31 |
32 | public bool Contains(KeyValuePair item)
33 | {
34 | return ((ICollection>)Headers).Contains(item);
35 | }
36 |
37 | public bool ContainsKey(string key)
38 | {
39 | return Headers.ContainsKey(key);
40 | }
41 |
42 | public void CopyTo(KeyValuePair[] array, int arrayIndex)
43 | {
44 | ((ICollection>)Headers).CopyTo(array, arrayIndex);
45 | }
46 |
47 | private static string[] CreateArrayCopy(string[] original)
48 | {
49 | string[] array = new string[original.Length];
50 | Array.Copy(original, array, original.Length);
51 | return array;
52 | }
53 |
54 | public IEnumerator> GetEnumerator()
55 | {
56 | return ((IEnumerable>)Headers).GetEnumerator();
57 | }
58 |
59 | public bool Remove(string key)
60 | {
61 | return Headers.Remove(key);
62 | }
63 |
64 | public bool Remove(KeyValuePair item)
65 | {
66 | return ((ICollection>)Headers).Remove(item);
67 | }
68 |
69 | IEnumerator IEnumerable.GetEnumerator()
70 | {
71 | return GetEnumerator();
72 | }
73 |
74 | public bool TryGetValue(string key, out string[] value)
75 | {
76 | string[] original;
77 | if (Headers.TryGetValue(key, out original))
78 | {
79 | value = CreateArrayCopy(original);
80 | return true;
81 | }
82 | value = null;
83 | return false;
84 | }
85 |
86 | public int Count
87 | {
88 | get
89 | {
90 | return Headers.Count;
91 | }
92 | }
93 |
94 | public bool IsReadOnly
95 | {
96 | get
97 | {
98 | return false;
99 | }
100 | }
101 |
102 | public string[] this[string key]
103 | {
104 | get
105 | {
106 | return CreateArrayCopy(Headers[key]);
107 | }
108 | set
109 | {
110 | Headers[key] = value;
111 | }
112 | }
113 |
114 | public ICollection Keys
115 | {
116 | get
117 | {
118 | return Headers.Keys;
119 | }
120 | }
121 |
122 | public ICollection Values
123 | {
124 | get
125 | {
126 | List list = Headers.Values.ToList();
127 | checked
128 | {
129 | for (int i = 0; i < list.Count; i++)
130 | {
131 | string[] array = list[i];
132 | list[i] = new string[]
133 | {
134 | array[0]
135 | };
136 | }
137 | return list;
138 | }
139 | }
140 | }
141 |
142 |
143 | }
144 | }
145 |
--------------------------------------------------------------------------------
/Demo/WebSocket.Demo2/Adapter.cs:
--------------------------------------------------------------------------------
1 | /***************************************************************
2 | * WebSocket 应用示例 之二
3 | * =============================================================
4 | * 本DEMO的目的意义:
5 | * 演示封装一个 WebSocket 对象
6 | *
7 | * 使用方法:将编译得到的dll放到网站的bin文件夹中。
8 | * *************************************************************/
9 |
10 |
11 | #region
12 |
13 | using System;
14 | using System.Collections.Generic;
15 | using System.Text;
16 | using System.Threading.Tasks;
17 | using System.IO;
18 | using System.Linq;
19 | using System.Threading;
20 |
21 | #endregion
22 |
23 |
24 | namespace WebSocket.Demo
25 | {
26 |
27 | ///
28 | /// owin/owindog For OWIN 接口类
29 | ///
30 | public class Adapter
31 | {
32 |
33 |
34 | ///
35 | /// OWIN适配器的主函数
36 | ///
37 | ///
38 | ///
39 | public Task OwinMain(IDictionary env)
40 | {
41 | //是否包含Websocket握手函数并尝试进行WebSocket连接
42 | if (env.ContainsKey("websocket.Accept"))
43 | {
44 | var websocket = new WebSocket(env);
45 |
46 | //if(websocket.RequestPath == ......)
47 |
48 | if (websocket.Accept())
49 | {
50 |
51 | websocket.OnSend = OnSend;
52 | websocket.OnClose = OnClose;
53 | websocket.OnRead = OnRead;
54 |
55 |
56 | // .....
57 | // websocket.RemoteIpAddress
58 | // .....
59 | // ......
60 |
61 | //开始接受远端数据
62 | //本方法只需在连接成功后调用一次。
63 | websocket.StartRead();
64 |
65 | //返回表示完成的任务
66 | return Task.Delay(0);
67 | }
68 | }
69 |
70 | //如果不是websocket请求,就接普通OWIN处理
71 | return ProcessRequest(env);
72 | }
73 |
74 |
75 |
76 | ///
77 | /// 数据接收事件
78 | ///
79 | ///
80 | ///
81 | void OnRead(object sender, string message)
82 | {
83 | var websocket = sender as WebSocket;
84 |
85 | if (message == "exit" || message == "close")
86 | {
87 | websocket.Close();
88 | return;
89 | }
90 |
91 | websocket.Send(message);
92 | }
93 |
94 |
95 | ///
96 | /// 数据发送完成的事件
97 | ///
98 | ///
99 | void OnSend(object sender)
100 | {
101 | /// ..... ////
102 | }
103 |
104 |
105 | ///
106 | /// 连接已经关闭
107 | ///
108 | ///
109 | void OnClose(object sender)
110 | {
111 | // ... ... //
112 | }
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 | ///
121 | /// 普通OWIN请求的处理函数
122 | ///
123 | ///
124 | ///
125 | private Task ProcessRequest(IDictionary env)
126 | {
127 |
128 | // 从字典中获取向客户(浏览器)发送数据的“流”对象
129 | /////////////////////////////////////////////////////////
130 | var responseStream = env["owin.ResponseBody"] as Stream;
131 |
132 | // 你准备发送的数据
133 | const string outString = "Owin ServerOwin Server!
Owin Server,放飞您灵感的翅膀...
\r\n";
134 | var outBytes = Encoding.UTF8.GetBytes(outString);
135 |
136 | // 从参数字典中获取Response HTTP头的字典对象
137 | var responseHeaders = env["owin.ResponseHeaders"] as IDictionary;
138 |
139 | // 设置必要的http响应头
140 | ////////////////////////////////////////////////////////////////
141 |
142 | // 设置 Content-Type头
143 | responseHeaders.Add("Content-Type", new[] { "text/html; charset=utf-8" });
144 |
145 |
146 | // 把正文写入流中,发送给浏览器
147 | responseStream.Write(outBytes, 0, outBytes.Length);
148 |
149 | return Task.FromResult(0);
150 |
151 | }
152 |
153 |
154 | }
155 |
156 |
157 |
158 | }
159 |
--------------------------------------------------------------------------------
/OwinDog/Util/SystemUtil.cs:
--------------------------------------------------------------------------------
1 |
2 | using Model;
3 |
4 | namespace Util
5 | {
6 | using System;
7 | using System.Runtime.InteropServices;
8 | using System.Security;
9 |
10 | public static class SystemUtil
11 | {
12 | private static unsafe string GetUname()
13 | {
14 | byte[] array = new byte[8192];
15 | string result;
16 | try
17 | {
18 | try
19 | {
20 | fixed (byte* ptr = array)
21 | {
22 | if (uname((IntPtr)((void*)ptr)) == 0)
23 | {
24 | result = Marshal.PtrToStringAnsi((IntPtr)((void*)ptr));
25 | return result;
26 | }
27 | }
28 | }
29 | finally
30 | {
31 | byte* ptr = null;
32 | }
33 | result = string.Empty;
34 | }
35 | catch
36 | {
37 | result = string.Empty;
38 | }
39 | return result;
40 | }
41 |
42 | public static bool IsWindowOs()
43 | {
44 | int platform = (int)Environment.OSVersion.Platform;
45 | return platform != 4 && platform != 6 && platform != 128;
46 | }
47 |
48 | public static void Init(LibUv b1)
49 | {
50 | if (b1.IsWindows)
51 | {
52 | InitLibWindows.InitLib(b1);
53 | return;
54 | }
55 | InitLibUnix.InitLib(b1);
56 | }
57 |
58 | public static bool IsDarwin()
59 | {
60 | return string.Equals(GetUname(), "Darwin", StringComparison.Ordinal);
61 | }
62 |
63 |
64 | [DllImport("libc", EntryPoint = "uname")]
65 | private static extern int uname(IntPtr entry);
66 | public static class InitLibUnix
67 | {
68 |
69 | public static void InitLib(LibUv libUv)
70 | {
71 | libUv.LoadLibrary = new Func(LoadLibrary);
72 | libUv.FreeLibrary = new Func(FreeLibrary);
73 | libUv.GetProcAddress = new Func(GetProcAddress);
74 | }
75 |
76 | public static bool FreeLibrary(IntPtr ptr1)
77 | {
78 | return (dlclose(ptr1) == 0);
79 | }
80 |
81 | public static IntPtr GetProcAddress(IntPtr ptr1, string text1)
82 | {
83 | dlerror();
84 | IntPtr ptr = dlsym(ptr1, text1);
85 | if (!(dlerror() == IntPtr.Zero))
86 | {
87 | return IntPtr.Zero;
88 | }
89 | return ptr;
90 | }
91 |
92 | public static IntPtr LoadLibrary(string text1)
93 | {
94 | return dlopen(text1, 2);
95 | }
96 |
97 |
98 | [SuppressUnmanagedCodeSecurity, DllImport("__Internal", EntryPoint="dlclose", SetLastError=true)]
99 | public static extern int dlclose(IntPtr aa);
100 |
101 |
102 | [SuppressUnmanagedCodeSecurity, DllImport("__Internal", EntryPoint = "dlerror", SetLastError = true)]
103 | public static extern IntPtr dlerror();
104 |
105 | [SuppressUnmanagedCodeSecurity, DllImport("__Internal", EntryPoint="dlsym", SetLastError=true)]
106 | public static extern IntPtr dlsym(IntPtr aa, string bb);
107 |
108 | [SuppressUnmanagedCodeSecurity, DllImport("__Internal", EntryPoint="dlopen", SetLastError=true)]
109 | public static extern IntPtr dlopen([MarshalAs(UnmanagedType.LPStr)] string aa, int bb);
110 | }
111 |
112 | public static class InitLibWindows
113 | {
114 | public static void InitLib(LibUv libUv)
115 | {
116 | libUv.LoadLibrary = new Func(LoadLibrary);
117 | libUv.FreeLibrary = new Func(FreeLibrary);
118 | libUv.GetProcAddress = new Func(GetProcAddress);
119 | }
120 |
121 | [DllImport("kernel32", EntryPoint="FreeLibrary")]
122 | public static extern bool FreeLibrary(IntPtr lib);
123 |
124 | [DllImport("kernel32", EntryPoint="LoadLibrary")]
125 | public static extern IntPtr LoadLibrary(string lib);
126 |
127 | [DllImport("kernel32", EntryPoint="GetProcAddress", CharSet=CharSet.Ansi, SetLastError=true, ExactSpelling=true)]
128 | public static extern IntPtr GetProcAddress(IntPtr p, string a);
129 | }
130 | }
131 | }
132 |
133 |
--------------------------------------------------------------------------------
/OwinDog/Service/ActionStoreManage.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Runtime.CompilerServices;
4 | using System.Runtime.ExceptionServices;
5 | using System.Runtime.InteropServices;
6 | using System.Threading;
7 | using System.Threading.Tasks;
8 | using System.Timers;
9 |
10 | namespace Service
11 | {
12 |
13 | public static class ActionStoreManage
14 | {
15 | private static readonly ActionStore _actionStore = new ActionStore();
16 |
17 | ///
18 | /// 添加action
19 | ///
20 | ///
21 | /// 所在的分组index
22 | public static int Add(Action action)
23 | {
24 | return _actionStore.AddAction(action, 30);
25 | }
26 |
27 | ///
28 | /// 根据所在的分组index 去删除包含的action
29 | ///
30 | /// 所在分组的index
31 | ///
32 | public static void Remove(int num, Action action)
33 | {
34 | _actionStore.RemoveAction(num, action);
35 | }
36 |
37 | ///
38 | /// 执行
39 | ///
40 | ///
41 | ///
42 | public static void Excute(object obj, ElapsedEventArgs elapsedEventArgs)
43 | {
44 | IList list = _actionStore.Get();
45 | if (list == null || list.Count < 1)
46 | {
47 | return;
48 | }
49 | foreach (Action current in list)
50 | {
51 | current();
52 | }
53 | }
54 |
55 |
56 | private class ActionStore
57 | {
58 | ///
59 | /// 共有120组
60 | ///
61 | private const int MaxSize = 120;
62 |
63 | ///
64 | /// 游标
65 | ///
66 | private int _index;
67 |
68 | private readonly object lockObject = new object();
69 |
70 | private readonly List[] ActionList = new List[MaxSize];
71 | public ActionStore()
72 | {
73 | //初始化
74 | for (int i = 0; i < ActionList.Length; i++)
75 | {
76 | ActionList[i] = new List();
77 | }
78 | }
79 |
80 | ///
81 | /// 获取组action 然后清空该组 且 游标自增
82 | ///
83 | ///
84 | public IList Get()
85 | {
86 |
87 | IList result;
88 | lock (lockObject)
89 | {
90 | if (ActionList[_index].Count < 1)
91 | {
92 | _index = (_index + 1) % MaxSize;//这种写法的好处是自增最大不会超过MaxSize
93 | result = null;
94 | }
95 | else
96 | {
97 | //去除分组下的所有的action集合
98 | IList list = ActionList[_index];
99 | //清空
100 | ActionList[_index] = new List();
101 | _index = (_index + 1) % MaxSize;
102 | //返回
103 | result = list;
104 | }
105 | }
106 | return result;
107 | }
108 |
109 | ///
110 | /// 分组 添加action
111 | ///
112 | ///
113 | ///
114 | ///
115 | public int AddAction(Action item, int num)
116 | {
117 | int result;
118 | lock (lockObject)
119 | {
120 | int num2 = (_index + num) % MaxSize;
121 | ActionList[num2].Add(item);
122 | result = num2;
123 | }
124 | return result;
125 | }
126 |
127 | ///
128 | /// 移除所在分组的action
129 | ///
130 | ///
131 | ///
132 | public void RemoveAction(int num, Action item)
133 | {
134 | if (num < 0 || num >= MaxSize)
135 | {
136 | return;
137 | }
138 | lock (lockObject)
139 | {
140 | if (ActionList[num].Contains(item))
141 | {
142 | ActionList[num].Remove(item);
143 | }
144 | }
145 | }
146 | }
147 | }
148 |
149 | }
150 |
--------------------------------------------------------------------------------
/OwinDog/Model/HandleBase.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Diagnostics;
3 | using System.Runtime.CompilerServices;
4 | using System.Runtime.InteropServices;
5 | using System.Threading;
6 |
7 | namespace Model
8 | {
9 | public abstract class HandleBase : SafeHandle
10 | {
11 | protected static LibUv.Close_Callback _Close_Callback = new LibUv.Close_Callback(Free);
12 |
13 | protected Action, object> _postAsync;
14 |
15 | //帮我们在地址和对象之间进行转换
16 | private GCHandle _GCHandle;
17 |
18 |
19 | protected HandleBase() : base(IntPtr.Zero, true)
20 | {
21 | }
22 |
23 | public LibUv LibUv { get; protected set; }
24 |
25 | ///
26 | /// 跑 loopRun的 线程Id
27 | ///
28 | public int LoopRunThreadId { get; set; }
29 |
30 |
31 |
32 |
33 | #region 释放
34 | protected static unsafe void Free(IntPtr intPtr)
35 | {
36 | if (intPtr == IntPtr.Zero)
37 | {
38 | return;
39 | }
40 | FreeHandle(intPtr, *(IntPtr*)((void*)intPtr));
41 | }
42 | protected static void FreeHandle(IntPtr intPtr, IntPtr intPtr2)
43 | {
44 | if (intPtr2 != IntPtr.Zero)
45 | {
46 | try
47 | {
48 | //返回从某个托管对象的句柄创建的新 GCHandle 对象
49 | GCHandle.FromIntPtr(intPtr2).Free();
50 | }
51 | catch
52 | {
53 | //ignore
54 | }
55 | }
56 | if (intPtr == IntPtr.Zero)
57 | {
58 | return;
59 | }
60 | //释放由非托管 COM 任务内存分配器使用 Marshal.AllocCoTaskMem 分配的内存块
61 | Marshal.FreeCoTaskMem(intPtr);
62 | }
63 | #endregion
64 | public void Debug(bool flag = false)
65 | {
66 | if (!flag && IsClosed)
67 | {
68 | Console.WriteLine("DEBUG: OwinDog.UvHandle.Validate: Handle is closed.");
69 | }
70 | if (IsInvalid)
71 | {
72 | Console.WriteLine("DEBUG: OwinDog.UvHandle.Validate: Handle is invalid.");
73 | }
74 | }
75 |
76 | public static unsafe T GetObjectFromHandel(IntPtr value)
77 | {
78 | return (T)((object)GCHandle.FromIntPtr(*(IntPtr*)((void*)value)).Target);
79 | }
80 |
81 |
82 |
83 | protected unsafe void Init(LibUv libuv, int hdle, int point)
84 | {
85 | LibUv = libuv;
86 | LoopRunThreadId = point;
87 | //Starting with libuv v1.0, users should allocate the memory for the loops before initializing it with uv_loop_init(uv_loop_t *). This allows you to plug in custom memory management
88 | handle = Marshal.AllocCoTaskMem(hdle);//申请内存
89 | *(IntPtr*)((void*)handle) = GCHandle.ToIntPtr(GCHandle.Alloc(this, GCHandleType.Weak));
90 | }
91 |
92 | public IntPtr InternalGetHandle()
93 | {
94 | return handle;
95 | }
96 |
97 | public virtual void Alloc()
98 | {
99 | _GCHandle = GCHandle.Alloc(this, GCHandleType.Normal);
100 | }
101 |
102 | public virtual void DoDispose()
103 | {
104 | _GCHandle.Free();
105 | }
106 |
107 | public void UvRef()
108 | {
109 | LibUv.UvRef(this);
110 | }
111 |
112 | public void UvUnRef()
113 | {
114 | LibUv.UvUnRef(this);
115 | }
116 |
117 | public override bool IsInvalid
118 | {
119 | get
120 | {
121 | return handle == IntPtr.Zero;
122 | }
123 | }
124 |
125 | protected override bool ReleaseHandle()
126 | {
127 | IntPtr intPtr = Interlocked.Exchange(ref handle, IntPtr.Zero);
128 | if (intPtr != IntPtr.Zero)
129 | {
130 | if (Thread.CurrentThread.ManagedThreadId != LoopRunThreadId)
131 | {
132 | if (_postAsync != null)
133 | {
134 | HandleRelease handleRelease = new HandleRelease();
135 | handleRelease.LibUv = LibUv;
136 | _postAsync(new Action