فهرست منبع

Merge branch 'master' of serset/Sers into develop

LithWang 10 ماه پیش
والد
کامیت
e02262af71
100فایلهای تغییر یافته به همراه4523 افزوده شده و 4591 حذف شده
  1. 0 31
      Publish/DevOps3/build-cmd/40.Station-publish(net5.0).bat
  2. 0 31
      Publish/DevOps3/build-cmd/40.Station-publish(netcoreapp2.1).bat
  3. 0 4
      dotnet/.editorconfig
  4. 1 3
      dotnet/Gateway/App.Gateway/App.Gateway.csproj
  5. 4 3
      dotnet/Gateway/App.Gateway/Program.cs
  6. 7 5
      dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.NamedPipe/DeliveryClient.cs
  7. 1 1
      dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.NamedPipe/DeliveryConnection.cs
  8. 2 2
      dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.NamedPipe/OrganizeClientBuilder.cs
  9. 1 1
      dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.NamedPipe/Sers.CL.Ipc.NamedPipe.csproj
  10. 1 1
      dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.SharedMemory/ConnConfig.cs
  11. 0 1
      dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.SharedMemory/DeliveryClient.cs
  12. 12 12
      dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.SharedMemory/DeliveryConnection.cs
  13. 1 1
      dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.SharedMemory/OrganizeClientBuilder.cs
  14. 1 1
      dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.SharedMemory/OrganizeServerBuilder.cs
  15. 5 5
      dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.SharedMemory/Stream/ReadStream.cs
  16. 1 1
      dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.SharedMemory/Stream/Util.cs
  17. 3 3
      dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.SharedMemory/Stream/WriteStream.cs
  18. 7 5
      dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Base/DeliveryClient_Base.cs
  19. 1 1
      dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Base/DeliveryConnection_Base.cs
  20. 4 2
      dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Base/DeliveryServer_Base.cs
  21. 5 3
      dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Mode/Simple/DeliveryClient.cs
  22. 0 1
      dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Mode/Simple/DeliveryConnection.cs
  23. 9 7
      dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Mode/Simple/DeliveryServer.cs
  24. 9 7
      dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Mode/ThreadWait/DeliveryClient.cs
  25. 3 1
      dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Mode/ThreadWait/DeliveryServer.cs
  26. 5 3
      dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Mode/Timer/DeliveryClient.cs
  27. 8 8
      dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Mode/Timer/DeliveryConnection.cs
  28. 6 4
      dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Mode/Timer/DeliveryServer.cs
  29. 4 4
      dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/OrganizeClientBuilder.cs
  30. 5 5
      dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/OrganizeServerBuilder.cs
  31. 1 1
      dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Sers.CL.Socket.Iocp.csproj
  32. 5 3
      dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.ThreadWait/DeliveryClient.cs
  33. 18 23
      dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.ThreadWait/DeliveryConnection.cs
  34. 1 1
      dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.ThreadWait/OrganizeClientBuilder.cs
  35. 2 2
      dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.ThreadWait/OrganizeServerBuilder.cs
  36. 1 1
      dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.ThreadWait/Sers.CL.Socket.ThreadWait.csproj
  37. 13 12
      dotnet/Library/Sers/Sers.CL/Test/CommunicationManage/CmClient/ProgramQps.cs
  38. 8 7
      dotnet/Library/Sers/Sers.CL/Test/CommunicationManage/CmClient/Statistics/StatisticsQpsInfo.cs
  39. 5 2
      dotnet/Library/Sers/Sers.CL/Test/CommunicationManage/CmServer/Program.cs
  40. 8 7
      dotnet/Library/Sers/Sers.CL/Test/CommunicationManage/CmServer/Statistics/StatisticsQpsInfo.cs
  41. 13 13
      dotnet/Library/Sers/Sers.CL/Test/MessageDelivery/DeliveryClient/Program.cs
  42. 8 7
      dotnet/Library/Sers/Sers.CL/Test/MessageDelivery/DeliveryClient/Statistics/StatisticsQpsInfo.cs
  43. 8 6
      dotnet/Library/Sers/Sers.CL/Test/MessageDelivery/DeliveryServer/Program.cs
  44. 8 7
      dotnet/Library/Sers/Sers.CL/Test/MessageDelivery/DeliveryServer/Statistics/StatisticsQpsInfo.cs
  45. 10 10
      dotnet/Library/Sers/Sers.CL/Test/MessageDelivery/DeliveryTest/Program.cs
  46. 9 7
      dotnet/Library/Sers/Sers.CL/WebSocket/Sers.CL.WebSocket/DeliveryClient.cs
  47. 10 11
      dotnet/Library/Sers/Sers.CL/WebSocket/Sers.CL.WebSocket/DeliveryClient_Connection.cs
  48. 7 7
      dotnet/Library/Sers/Sers.CL/WebSocket/Sers.CL.WebSocket/DeliveryServer_Connection.cs
  49. 0 1
      dotnet/Library/Sers/Sers.CL/WebSocket/Sers.CL.WebSocket/OrganizeClientBuilder.cs
  50. 0 1
      dotnet/Library/Sers/Sers.CL/WebSocket/Sers.CL.WebSocket/OrganizeServerBuilder.cs
  51. 1 1
      dotnet/Library/Sers/Sers.CL/WebSocket/Sers.CL.WebSocket/Sers.CL.WebSocket.csproj
  52. 4 4
      dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/DeliveryClient.cs
  53. 7 8
      dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/DeliveryConnection.cs
  54. 10 10
      dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/DeliveryServer.cs
  55. 1 1
      dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/OrganizeServerBuilder.cs
  56. 5 5
      dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/SocketStream.cs
  57. 38 38
      dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/Zmq/DispoIntPtr.cs
  58. 294 296
      dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/Zmq/Platform.cs
  59. 105 107
      dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/Zmq/ZContext.cs
  60. 62 66
      dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/Zmq/ZError.cs
  61. 132 134
      dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/Zmq/ZSocket.cs
  62. 16 20
      dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/Zmq/ZSocketFlags.cs
  63. 82 82
      dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/Zmq/ZSocketOption.cs
  64. 68 68
      dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/Zmq/ZSocketType.cs
  65. 429 420
      dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/Zmq/zmq.cs
  66. 8 9
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/Sers.CL.ClrZmq.ThreadWait/DeliveryClient.cs
  67. 7 8
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/Sers.CL.ClrZmq.ThreadWait/DeliveryConnection.cs
  68. 2 2
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/Sers.CL.ClrZmq.ThreadWait/DeliveryServer.cs
  69. 1 1
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/Sers.CL.ClrZmq.ThreadWait/OrganizeServerBuilder.cs
  70. 18 18
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/Sers.CL.ClrZmq.ThreadWait/SocketPoller4.cs
  71. 57 59
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Devices/PubSubDevice.cs
  72. 54 54
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Devices/PushPullDevice.cs
  73. 57 57
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Devices/RouterDealerDevice.cs
  74. 208 211
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Devices/StreamDealerDevice.cs
  75. 259 263
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Monitoring/ZMonitor.cs
  76. 22 22
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Monitoring/ZMonitorEventArgs.cs
  77. 7 7
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Monitoring/ZMonitorEventData.cs
  78. 56 56
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Monitoring/ZMonitorEvents.cs
  79. 33 32
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Monitoring/ZMonitorFileDescriptorEventArgs.cs
  80. 15 15
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Monitoring/ZMonitorIntervalEventArgs.cs
  81. 74 75
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Monitoring/ZMonitors.cs
  82. 23 26
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/DispoIntPtr.Ansi.cs
  83. 120 124
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/DispoIntPtr.cs
  84. 10 10
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/Platform.MacOSX.cs
  85. 249 248
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/Platform.Posix.cs
  86. 206 205
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/Platform.Win32.cs
  87. 30 31
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/Platform.__Internal.cs
  88. 294 296
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/Platform.cs
  89. 84 87
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/UnmanagedLibrary.cs
  90. 408 399
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/zmq.cs
  91. 41 41
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/zmq_pollitem_posix_t.cs
  92. 41 41
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/zmq_pollitem_windows_t.cs
  93. 16 16
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/RouterMandatory.cs
  94. 18 18
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/TcpKeepaliveBehaviour.cs
  95. 155 154
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Z85.cs
  96. 110 112
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/ZActor.cs
  97. 1 1
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/ZAuth.cs
  98. 3 3
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/ZCert.cs
  99. 2 4
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/ZCertStore.cs
  100. 339 340
      dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/ZContext.cs

+ 0 - 31
Publish/DevOps3/build-cmd/40.Station-publish(net5.0).bat

@@ -1,31 +0,0 @@
-@echo off
-
-
-:: #1 init
-set netVersion=net5.0
-
-
-:: #2 change netcore version
-VsTool.exe replace -r --path "../../.." --file "App.Gateway.csproj|App.Gover.Gateway.csproj|App.ServiceCenter.csproj|Did.SersLoader.Demo.csproj|App.Robot.Station.csproj" --old "<TargetFramework>net6.0</TargetFramework>" --new "<TargetFramework>%netVersion%</TargetFramework>"
-
-
-
-
-
-:: #3 publish
-call "40.Station-publish.bat"
-
-
-
-
-
-
-:: #4 revert netcore version
-VsTool.exe replace -r --path "../../.." --file "App.Gateway.csproj|App.Gover.Gateway.csproj|App.ServiceCenter.csproj|Did.SersLoader.Demo.csproj|App.Robot.Station.csproj" --old "<TargetFramework>%netVersion%</TargetFramework>" --new "<TargetFramework>net6.0</TargetFramework>"
-
-
-
-
-
-echo %~n0.bat success
-cd /d "%curPath%"

+ 0 - 31
Publish/DevOps3/build-cmd/40.Station-publish(netcoreapp2.1).bat

@@ -1,31 +0,0 @@
-@echo off
-
-
-:: #1 init
-set netVersion=netcoreapp2.1
-
-
-:: #2 change netcore version
-VsTool.exe replace -r --path "../../.." --file "App.Gateway.csproj|App.Gover.Gateway.csproj|App.ServiceCenter.csproj|Did.SersLoader.Demo.csproj|App.Robot.Station.csproj" --old "<TargetFramework>net6.0</TargetFramework>" --new "<TargetFramework>%netVersion%</TargetFramework>"
-
-
-
-
-
-:: #3 publish
-call "40.Station-publish.bat"
-
-
-
-
-
-
-:: #4 revert netcore version
-VsTool.exe replace -r --path "../../.." --file "App.Gateway.csproj|App.Gover.Gateway.csproj|App.ServiceCenter.csproj|Did.SersLoader.Demo.csproj|App.Robot.Station.csproj" --old "<TargetFramework>%netVersion%</TargetFramework>" --new "<TargetFramework>net6.0</TargetFramework>"
-
-
-
-
-
-echo %~n0.bat success
-cd /d "%curPath%"

+ 0 - 4
dotnet/.editorconfig

@@ -1,4 +0,0 @@
-[*.cs]
-
-# CS1591: 缺少对公共可见类型或成员的 XML 注释
-dotnet_diagnostic.CS1591.severity = none

+ 1 - 3
dotnet/Gateway/App.Gateway/App.Gateway.csproj

@@ -8,7 +8,7 @@
     <PropertyGroup>
         <OutputType>Exe</OutputType>
         <TargetFramework>net6.0</TargetFramework>
-        <Version>2.1.25-temp</Version>
+        <Version>2.1.25</Version>
         <PackageProjectUrl>https://github.com/serset/Sers</PackageProjectUrl>
     </PropertyGroup>
 
@@ -24,8 +24,6 @@
     </ItemGroup>
 
     <ItemGroup>
-        <PackageReference Include="Microsoft.AspNetCore.App" />
-
         <ProjectReference Include="..\..\Library\Sers\Sers.CL\Ipc\Sers.CL.Ipc.SharedMemory\Sers.CL.Ipc.SharedMemory.csproj" />
         <ProjectReference Include="..\..\Library\Sers\Sers.CL\WebSocket\Sers.CL.WebSocket\Sers.CL.WebSocket.csproj" />
         <ProjectReference Include="..\..\Library\Sers\Sers.CL\Zmq\FullDuplex\Sers.CL.Zmq.FullDuplex\Sers.CL.Zmq.FullDuplex.csproj" />

+ 4 - 3
dotnet/Gateway/App.Gateway/Program.cs

@@ -1,6 +1,8 @@
 using System;
+
 using Sers.Gateway;
 using Sers.ServiceStation;
+
 using Vit.Core.Module.Log;
 
 namespace App.Gateway
@@ -12,16 +14,15 @@ namespace App.Gateway
             try
             {
 
-                #region (x.1)初始化ServiceStation
+                #region init ServiceStation
                 ServiceStation.Init();
 
                 //ServiceStation.Discovery(typeof(Program).Assembly);
                 if (!ServiceStation.Start())
                 {
-                    Logger.Error("无法连接服务中心。站点关闭");
+                    Logger.Error("can not connect to ServiceCenter. Closing station now.");
                     return;
                 }
-
                 #endregion
 
                 GatewayHelp.Bridge();

+ 7 - 5
dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.NamedPipe/DeliveryClient.cs

@@ -1,11 +1,13 @@
 using System;
 using System.IO.Pipes;
+
 using Sers.Core.CL.MessageDelivery;
+
 using Vit.Core.Module.Log;
 
 namespace Sers.CL.Ipc.NamedPipe
 {
-    public class DeliveryClient: IDeliveryClient
+    public class DeliveryClient : IDeliveryClient
     {
 
         /// <summary>
@@ -13,7 +15,7 @@ namespace Sers.CL.Ipc.NamedPipe
         /// </summary>
         public int connectTimeoutMs = 1000;
 
-        DeliveryConnection _conn  = new DeliveryConnection();
+        DeliveryConnection _conn = new DeliveryConnection();
         public IDeliveryConnection conn => _conn;
 
         /// <summary>
@@ -21,7 +23,7 @@ namespace Sers.CL.Ipc.NamedPipe
         /// </summary>
         public Action<IDeliveryConnection, ArraySegment<byte>> Conn_OnGetFrame { set { _conn.OnGetFrame = value; } }
 
-        public Action<IDeliveryConnection> Conn_OnDisconnected { set=> _conn.Conn_OnDisconnected=value; }
+        public Action<IDeliveryConnection> Conn_OnDisconnected { set => _conn.Conn_OnDisconnected = value; }
 
 
         /// <summary>
@@ -32,7 +34,7 @@ namespace Sers.CL.Ipc.NamedPipe
         /// 默认 "Sers.CL.Ipc"
         /// </summary>
         public string pipeName = "Sers.CL.Ipc";
- 
+
 
         public bool Connect()
         {
@@ -58,7 +60,7 @@ namespace Sers.CL.Ipc.NamedPipe
                 Logger.Error("[CL.DeliveryClient] Ipc.NamedPipe, connect - Error", ex);
                 return false;
             }
-             
+
 
             _conn.Init(client);
 

+ 1 - 1
dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.NamedPipe/DeliveryConnection.cs

@@ -183,7 +183,7 @@ namespace Sers.CL.Ipc.NamedPipe
         }
 
 
-        PipeFrame pipe = new PipeFrame() { OnDequeueData = ArraySegmentBytePool_Extensions.ReturnToPool };
+        readonly PipeFrame pipe = new PipeFrame() { OnDequeueData = ArraySegmentBytePool_Extensions.ReturnToPool };
 
         public void AppendData(ArraySegment<byte> data)
         {

+ 2 - 2
dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.NamedPipe/OrganizeClientBuilder.cs

@@ -25,9 +25,9 @@ namespace Sers.CL.Ipc.NamedPipe
 
 
             delivery.serverName = config["serverName"].ConvertToString();
-            delivery.pipeName = config["pipeName"].ConvertToString();      
+            delivery.pipeName = config["pipeName"].ConvertToString();
 
-            organizeList.Add(new OrganizeClient(delivery, config)); 
+            organizeList.Add(new OrganizeClient(delivery, config));
         }
     }
 }

+ 1 - 1
dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.NamedPipe/Sers.CL.Ipc.NamedPipe.csproj

@@ -6,7 +6,7 @@
 
     <PropertyGroup>
         <TargetFramework>netstandard2.0</TargetFramework>
-        <Version>2.1.25-temp</Version>
+        <Version>2.1.25</Version>
     </PropertyGroup>
 
     <PropertyGroup>

+ 1 - 1
dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.SharedMemory/ConnConfig.cs

@@ -1,7 +1,7 @@
 namespace Sers.CL.Ipc.SharedMemory
 {
     class ConnConfig
-    { 
+    {
 
         /// <summary>
         /// 共享内存名称

+ 0 - 1
dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.SharedMemory/DeliveryClient.cs

@@ -1,6 +1,5 @@
 using System;
 
-using Sers.CL.Ipc.SharedMemory.Stream;
 using Sers.Core.CL.MessageDelivery;
 
 using Vit.Core.Module.Log;

+ 12 - 12
dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.SharedMemory/DeliveryConnection.cs

@@ -1,5 +1,4 @@
 using System;
-using System.Collections.Generic;
 
 using Sers.CL.Ipc.SharedMemory.Stream;
 using Sers.Core.CL.MessageDelivery;
@@ -14,7 +13,7 @@ namespace Sers.CL.Ipc.SharedMemory
 
         public DeliveryConnection()
         {
-            readStream = new ReadStream() { conn=this};
+            readStream = new ReadStream() { conn = this };
             writeStream = new WriteStream();
         }
 
@@ -28,7 +27,8 @@ namespace Sers.CL.Ipc.SharedMemory
         public byte state { get; set; } = DeliveryConnState.waitForCertify;
 
 
-        public Action<IDeliveryConnection, ArraySegment<byte>> OnGetFrame {
+        public Action<IDeliveryConnection, ArraySegment<byte>> OnGetFrame
+        {
             set
             {
                 if (_securityManager != null)
@@ -45,20 +45,20 @@ namespace Sers.CL.Ipc.SharedMemory
 
         public Action<IDeliveryConnection> OnDisconnected { set => readStream.OnDisconnected = value; }
 
-        WriteStream writeStream;
-        ReadStream readStream;
+        readonly WriteStream writeStream;
+        readonly ReadStream readStream;
 
 
 
-        public bool InitAsServer(string memoryName,int nodeCount,int nodeBufferSize)
+        public bool InitAsServer(string memoryName, int nodeCount, int nodeBufferSize)
         {
             if (!writeStream.SharedMemory_Malloc(memoryName + ".ServerToClient", nodeCount, nodeBufferSize))
-            {               
+            {
                 return false;
             }
 
             if (!readStream.SharedMemory_Malloc(memoryName + ".ClientToServer", nodeCount, nodeBufferSize))
-            {               
+            {
                 return false;
             }
             return true;
@@ -68,12 +68,12 @@ namespace Sers.CL.Ipc.SharedMemory
         public bool InitAsClient(string memoryName)
         {
             if (!writeStream.SharedMemory_Attach(memoryName + ".ClientToServer"))
-            {              
+            {
                 return false;
             }
 
             if (!readStream.SharedMemory_Attach(memoryName + ".ServerToClient"))
-            {           
+            {
                 return false;
             }
             return true;
@@ -83,12 +83,12 @@ namespace Sers.CL.Ipc.SharedMemory
         public bool Start()
         {
             if (!readStream.Start())
-            {              
+            {
                 return false;
             }
             if (!writeStream.Start())
             {
-                
+
                 return false;
             }
             return true;

+ 1 - 1
dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.SharedMemory/OrganizeClientBuilder.cs

@@ -32,6 +32,6 @@ namespace Sers.CL.Ipc.SharedMemory
         }
 
 
-        
+
     }
 }

+ 1 - 1
dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.SharedMemory/OrganizeServerBuilder.cs

@@ -32,6 +32,6 @@ namespace Sers.CL.Ipc.SharedMemory
             organizeList.Add(new OrganizeServer(delivery, config));
         }
 
-         
+
     }
 }

+ 5 - 5
dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.SharedMemory/Stream/ReadStream.cs

@@ -52,7 +52,7 @@ namespace Sers.CL.Ipc.SharedMemory.Stream
                 Logger.Error(ex);
                 return false;
             }
-           
+
         }
 
         public bool SharedMemory_Attach(string name = "")
@@ -76,7 +76,7 @@ namespace Sers.CL.Ipc.SharedMemory.Stream
             if (buffer == null) return false;
 
             // start receiveMsg Thread
-            receiveMsg_Thread.threadName = "CL-Ipc-SharedMemory-receiveMsg-"+ buffer.Name;
+            receiveMsg_Thread.threadName = "CL-Ipc-SharedMemory-receiveMsg-" + buffer.Name;
             receiveMsg_Thread.threadCount = 1;
             receiveMsg_Thread.Processor = ReceiveMsg_Thread;
             receiveMsg_Thread.Start();
@@ -85,8 +85,8 @@ namespace Sers.CL.Ipc.SharedMemory.Stream
             return true;
         }
 
- 
-      
+
+
 
         public void Stop()
         {
@@ -112,7 +112,7 @@ namespace Sers.CL.Ipc.SharedMemory.Stream
 
         #region ReceiveMsg_Thread
 
-        LongThread receiveMsg_Thread = new LongThread();
+        readonly LongThread receiveMsg_Thread = new LongThread();
 
         void ReceiveMsg_Thread()
         {

+ 1 - 1
dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.SharedMemory/Stream/Util.cs

@@ -12,7 +12,7 @@
         /// <param name="nodeBufferSize">共享内存节点大小</param>
         /// <returns></returns>
         public static global::SharedMemory.CircularBuffer SharedMemory_Malloc(string name, int nodeCount, int nodeBufferSize)
-        {             
+        {
             string ipcName = "sers.ipc." + name;
             return new global::SharedMemory.CircularBuffer(name: ipcName, nodeCount: nodeCount, nodeBufferSize: nodeBufferSize);
         }

+ 3 - 3
dotnet/Library/Sers/Sers.CL/Ipc/Sers.CL.Ipc.SharedMemory/Stream/WriteStream.cs

@@ -12,7 +12,7 @@ namespace Sers.CL.Ipc.SharedMemory.Stream
     {
 
         //public Action  OnDisconnected;
-        public WriteStream(int boundedCapacity= 10000000)
+        public WriteStream(int boundedCapacity = 10000000)
         {
             msgToSend = new BlockingCollection<byte[]>(boundedCapacity);
         }
@@ -80,9 +80,9 @@ namespace Sers.CL.Ipc.SharedMemory.Stream
             return true;
         }
 
-     
 
-       
+
+
 
         public void SendMessageAsync(byte[] msg)
         {

+ 7 - 5
dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Base/DeliveryClient_Base.cs

@@ -6,7 +6,9 @@ using System.Net.Sockets;
 using System.Runtime.CompilerServices;
 using System.Threading;
 using System.Threading.Tasks;
+
 using Sers.Core.CL.MessageDelivery;
+
 using Vit.Core.Module.Log;
 using Vit.Core.Util.Net;
 using Vit.Core.Util.Pool;
@@ -14,7 +16,7 @@ using Vit.Core.Util.Pool;
 namespace Sers.CL.Socket.Iocp.Base
 {
     public class DeliveryClient_Base<DeliveryConnection> : IDeliveryClient
-        where DeliveryConnection : DeliveryConnection_Base,new()
+        where DeliveryConnection : DeliveryConnection_Base, new()
     {
         public virtual DeliveryConnection NewConnection()
         {
@@ -104,8 +106,8 @@ namespace Sers.CL.Socket.Iocp.Base
                 if (connectArgs.SocketError != SocketError.Success)
                 {
                     return false;
-                }          
-                 
+                }
+
                 return true;
 
             }
@@ -210,7 +212,7 @@ namespace Sers.CL.Socket.Iocp.Base
                         {
                             ProcessReceive(e);
                         });
-                    }           
+                    }
                     return;
                 }
             }
@@ -224,7 +226,7 @@ namespace Sers.CL.Socket.Iocp.Base
         #endregion
 
 
-   
+
 
 
 

+ 1 - 1
dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Base/DeliveryConnection_Base.cs

@@ -117,7 +117,7 @@ namespace Sers.CL.Socket.Iocp.Base
 
 
 
-        [MethodImpl(MethodImplOptions.AggressiveInlining)] 
+        [MethodImpl(MethodImplOptions.AggressiveInlining)]
         public abstract void SendFrameAsync(ByteData data);
     }
 }

+ 4 - 2
dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Base/DeliveryServer_Base.cs

@@ -9,7 +9,9 @@ using System.Net.Sockets;
 using System.Runtime.CompilerServices;
 using System.Threading;
 using System.Threading.Tasks;
+
 using Sers.Core.CL.MessageDelivery;
+
 using Vit.Core.Module.Log;
 using Vit.Core.Util.Net;
 using Vit.Core.Util.Pool;
@@ -127,7 +129,7 @@ namespace Sers.CL.Socket.Iocp.Base
         /// 停止服务
         /// </summary>
         public virtual void Stop()
-        {     
+        {
 
             if (listenSocket == null) return;
 
@@ -319,7 +321,7 @@ namespace Sers.CL.Socket.Iocp.Base
         #endregion
 
 
-    
+
 
 
         #region Delivery_Event

+ 5 - 3
dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Mode/Simple/DeliveryClient.cs

@@ -1,13 +1,15 @@
 using System;
+
 using Sers.CL.Socket.Iocp.Base;
+
 using Vit.Core.Module.Log;
 
 namespace Sers.CL.Socket.Iocp.Mode.Simple
 {
     public class DeliveryClient : DeliveryClient_Base<DeliveryConnection>
-    {         
+    {
+
 
-         
         public override bool Connect()
         {
             try
@@ -15,7 +17,7 @@ namespace Sers.CL.Socket.Iocp.Mode.Simple
                 Logger.Info("[CL.DeliveryClient] Socket.Iocp,connecting", new { host, port });
 
 
-                if (!base.Connect()) 
+                if (!base.Connect())
                 {
                     return false;
                 }

+ 0 - 1
dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Mode/Simple/DeliveryConnection.cs

@@ -5,7 +5,6 @@ using System.Runtime.CompilerServices;
 using Sers.CL.Socket.Iocp.Base;
 
 using Vit.Core.Module.Log;
-using Vit.Extensions;
 using Vit.Extensions.Json_Extensions;
 
 namespace Sers.CL.Socket.Iocp.Mode.Simple

+ 9 - 7
dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Mode/Simple/DeliveryServer.cs

@@ -1,20 +1,22 @@
 using System;
+
 using Sers.CL.Socket.Iocp.Base;
+
 using Vit.Core.Module.Log;
 
 namespace Sers.CL.Socket.Iocp.Mode.Simple
 {
-    public class DeliveryServer:  DeliveryServer_Base<DeliveryConnection>
-    { 
- 
-    
+    public class DeliveryServer : DeliveryServer_Base<DeliveryConnection>
+    {
+
+
         public override bool Start()
-        {  
+        {
             try
             {
                 Logger.Info("[CL.DeliveryServer] Socket.Iocp,starting", new { host, port });
 
-                if (!base.Start()) 
+                if (!base.Start())
                 {
                     return false;
                 }
@@ -27,7 +29,7 @@ namespace Sers.CL.Socket.Iocp.Mode.Simple
                 Logger.Error(ex);
             }
             return false;
-        } 
+        }
 
 
     }

+ 9 - 7
dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Mode/ThreadWait/DeliveryClient.cs

@@ -1,8 +1,10 @@
 using System;
 using System.Runtime.CompilerServices;
 using System.Threading;
+
 using Sers.CL.Socket.Iocp.Base;
 using Sers.CL.Socket.Iocp.Mode.Timer;
+
 using Vit.Core.Module.Log;
 using Vit.Core.Util.Threading.Worker;
 
@@ -46,7 +48,7 @@ namespace Sers.CL.Socket.Iocp.Mode.ThreadWait
                     return false;
                 }
 
-                           
+
                 //(x.4)   
                 Send_task.threadCount = 1;
                 Send_task.Processor = Send_Flush;
@@ -75,7 +77,7 @@ namespace Sers.CL.Socket.Iocp.Mode.ThreadWait
             {
                 Logger.Error(ex);
             }
-        
+
 
             base.Close();
         }
@@ -93,24 +95,24 @@ namespace Sers.CL.Socket.Iocp.Mode.ThreadWait
 
         LongThread Send_task = new LongThread();
 
- 
+
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         void Send_Flush()
         {
-            while (true) 
+            while (true)
             {
                 try
                 {
                     _conn.FlushSendFrameQueue();
- 
+
                     //global::System.Threading.SpinWait.SpinUntil(() => false, sendFlushInterval);
-                    Thread.Sleep(sendFlushInterval); 
+                    Thread.Sleep(sendFlushInterval);
                 }
                 catch (Exception ex) when (!(ex.GetBaseException() is ThreadInterruptedException))
                 {
                     Logger.Error(ex);
                 }
-            }           
+            }
         }
 
         #endregion

+ 3 - 1
dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Mode/ThreadWait/DeliveryServer.cs

@@ -1,8 +1,10 @@
 using System;
 using System.Runtime.CompilerServices;
 using System.Threading;
+
 using Sers.CL.Socket.Iocp.Base;
 using Sers.CL.Socket.Iocp.Mode.Timer;
+
 using Vit.Core.Module.Log;
 using Vit.Core.Util.Threading.Worker;
 
@@ -110,7 +112,7 @@ namespace Sers.CL.Socket.Iocp.Mode.ThreadWait
                 {
                     Logger.Error(ex);
                 }
-            }            
+            }
         }
 
         #endregion         

+ 5 - 3
dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Mode/Timer/DeliveryClient.cs

@@ -1,6 +1,8 @@
 using System;
 using System.Runtime.CompilerServices;
+
 using Sers.CL.Socket.Iocp.Base;
+
 using Vit.Core.Module.Log;
 using Vit.Core.Util.Threading.Timer;
 
@@ -58,7 +60,7 @@ namespace Sers.CL.Socket.Iocp.Mode.Timer
             }
             return false;
 
-          
+
         }
 
 
@@ -71,9 +73,9 @@ namespace Sers.CL.Socket.Iocp.Mode.Timer
             catch (Exception ex)
             {
                 Logger.Error(ex);
-            }    
+            }
+
 
-            
             base.Close();
         }
         #endregion

+ 8 - 8
dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Mode/Timer/DeliveryConnection.cs

@@ -29,17 +29,17 @@ namespace Sers.CL.Socket.Iocp.Mode.Timer
         /// <summary>
         /// 发送缓冲区数据块的最小大小(单位:byte)
         /// </summary>
-        public int sendBufferSize ;
+        public int sendBufferSize;
 
         /// <summary>
         /// 发送缓冲区个数
         /// </summary>
         int sendBufferCount;
 
-        ByteData[] buffer ;
-        int[] bufferItemCount ;
+        ByteData[] buffer;
+        int[] bufferItemCount;
+
 
-   
 
 
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -54,7 +54,7 @@ namespace Sers.CL.Socket.Iocp.Mode.Timer
         public void FlushSendFrameQueue()
         {
             int curIndex;
-             
+
             try
             {
                 while (true)
@@ -99,7 +99,7 @@ namespace Sers.CL.Socket.Iocp.Mode.Timer
         /// <param name="stopIndex">不包含</param>
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         void FlushData(int stopIndex)
-        {      
+        {
             int curCount;
             ByteData byteData;
             byte[] bytes;
@@ -140,7 +140,7 @@ namespace Sers.CL.Socket.Iocp.Mode.Timer
 
                     sumCount = 0;
                     startIndex = curIndex;
-                }           
+                }
             }
         }
 
@@ -152,7 +152,7 @@ namespace Sers.CL.Socket.Iocp.Mode.Timer
         /// <param name="sumCount"></param>
         /// <returns></returns>
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        unsafe byte[] BufferToBytes(int startIndex, int stopIndex,int sumCount)
+        unsafe byte[] BufferToBytes(int startIndex, int stopIndex, int sumCount)
         {
             var bytes = new byte[sumCount + (stopIndex - startIndex) * 4];
 

+ 6 - 4
dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Mode/Timer/DeliveryServer.cs

@@ -1,6 +1,8 @@
 using System;
 using System.Runtime.CompilerServices;
+
 using Sers.CL.Socket.Iocp.Base;
+
 using Vit.Core.Module.Log;
 using Vit.Core.Util.Threading.Timer;
 
@@ -10,7 +12,7 @@ namespace Sers.CL.Socket.Iocp.Mode.Timer
     {
 
         #region NewConnection
-      
+
         /// <summary>
         /// 发送缓冲区数据块的最小大小(单位:byte,默认 1000000)
         /// </summary>
@@ -58,7 +60,7 @@ namespace Sers.CL.Socket.Iocp.Mode.Timer
             }
             return false;
         }
- 
+
 
 
         /// <summary>
@@ -75,7 +77,7 @@ namespace Sers.CL.Socket.Iocp.Mode.Timer
                 Logger.Error(ex);
             }
 
-            base.Stop(); 
+            base.Stop();
         }
         #endregion
 
@@ -110,7 +112,7 @@ namespace Sers.CL.Socket.Iocp.Mode.Timer
 
         #endregion
 
- 
+
 
     }
 }

+ 4 - 4
dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/OrganizeClientBuilder.cs

@@ -21,7 +21,7 @@ namespace Sers.CL.Socket.Iocp
                 securityManager = Sers.Core.Util.StreamSecurity.SecurityManager.BuildSecurityManager(securityConfigs);
             }
             #endregion
- 
+
 
 
             string mode = config["mode"]?.ToString();
@@ -29,7 +29,7 @@ namespace Sers.CL.Socket.Iocp
             switch (mode)
             {
                 default:
-                //case "Simple":
+                    //case "Simple":
                     {
                         var delivery = new Mode.Simple.DeliveryClient();
 
@@ -76,7 +76,7 @@ namespace Sers.CL.Socket.Iocp
                         organizeList.Add(new OrganizeClient(delivery, config));
                     }
                     break;
-                case "ThreadWait":           
+                case "ThreadWait":
                     {
                         var delivery = new Mode.ThreadWait.DeliveryClient();
 
@@ -98,7 +98,7 @@ namespace Sers.CL.Socket.Iocp
                         delivery.sendBufferSize = config["sendBufferSize"].ConvertBySerialize<int?>() ?? delivery.sendBufferSize;
 
                         // 发送缓冲区个数(默认1024)  
-                        delivery.sendBufferCount = config["sendBufferCount"].ConvertBySerialize<int?>() ?? delivery.sendBufferSize;                         
+                        delivery.sendBufferCount = config["sendBufferCount"].ConvertBySerialize<int?>() ?? delivery.sendBufferSize;
                         #endregion
 
                         organizeList.Add(new OrganizeClient(delivery, config));

+ 5 - 5
dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/OrganizeServerBuilder.cs

@@ -22,14 +22,14 @@ namespace Sers.CL.Socket.Iocp
                 securityManager = Sers.Core.Util.StreamSecurity.SecurityManager.BuildSecurityManager(securityConfigs);
             }
             #endregion
- 
+
 
             string mode = config["mode"]?.ToString();
 
             switch (mode)
             {
                 default:
-                //case "Simple":
+                    //case "Simple":
                     {
                         var delivery = new Mode.Simple.DeliveryServer();
 
@@ -46,7 +46,7 @@ namespace Sers.CL.Socket.Iocp
                         organizeList.Add(new OrganizeServer(delivery, config));
                     }
                     break;
-                case "Timer":              
+                case "Timer":
                     {
                         var delivery = new Mode.Timer.DeliveryServer();
 
@@ -74,7 +74,7 @@ namespace Sers.CL.Socket.Iocp
                         organizeList.Add(new OrganizeServer(delivery, config));
                     }
                     break;
-                 case "ThreadWait":           
+                case "ThreadWait":
                     {
                         var delivery = new Mode.ThreadWait.DeliveryServer();
 
@@ -107,6 +107,6 @@ namespace Sers.CL.Socket.Iocp
 
 
         }
-       
+
     }
 }

+ 1 - 1
dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.Iocp/Sers.CL.Socket.Iocp.csproj

@@ -6,7 +6,7 @@
 
     <PropertyGroup>
         <TargetFramework>netstandard2.0</TargetFramework>
-        <Version>2.1.25-temp</Version>
+        <Version>2.1.25</Version>
     </PropertyGroup>
 
     <PropertyGroup>

+ 5 - 3
dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.ThreadWait/DeliveryClient.cs

@@ -1,14 +1,16 @@
 using System;
 using System.Net.Sockets;
+
 using Sers.Core.CL.MessageDelivery;
+
 using Vit.Core.Module.Log;
 
 namespace Sers.CL.Socket.ThreadWait
 {
-    public class DeliveryClient: IDeliveryClient
+    public class DeliveryClient : IDeliveryClient
     {
 
-        DeliveryConnection _conn  = new DeliveryConnection();
+        DeliveryConnection _conn = new DeliveryConnection();
         public IDeliveryConnection conn => _conn;
 
 
@@ -17,7 +19,7 @@ namespace Sers.CL.Socket.ThreadWait
         /// </summary>
         public Action<IDeliveryConnection, ArraySegment<byte>> Conn_OnGetFrame { set { _conn.OnGetFrame = value; } }
 
-        public Action<IDeliveryConnection> Conn_OnDisconnected { set=> _conn.Conn_OnDisconnected=value; }
+        public Action<IDeliveryConnection> Conn_OnDisconnected { set => _conn.Conn_OnDisconnected = value; }
 
 
 

+ 18 - 23
dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.ThreadWait/DeliveryConnection.cs

@@ -1,5 +1,4 @@
 using System;
-using System.Collections.Concurrent;
 using System.Net.Sockets;
 using System.Runtime.CompilerServices;
 using System.Threading;
@@ -7,17 +6,15 @@ using System.Threading;
 using Sers.Core.CL.MessageDelivery;
 
 using Vit.Core.Module.Log;
-using Vit.Core.Util.Pipelines;
 using Vit.Core.Util.Pool;
 using Vit.Core.Util.Threading.Worker;
-using Vit.Extensions;
 using Vit.Extensions.Json_Extensions;
 
 namespace Sers.CL.Socket.ThreadWait
 {
-    public class DeliveryConnection: IDeliveryConnection
+    public class DeliveryConnection : IDeliveryConnection
     {
- 
+
         ~DeliveryConnection()
         {
             Close();
@@ -32,7 +29,7 @@ namespace Sers.CL.Socket.ThreadWait
         public byte state { get; set; } = DeliveryConnState.waitForCertify;
 
 
-        public Action<IDeliveryConnection > Conn_OnDisconnected { get; set; }
+        public Action<IDeliveryConnection> Conn_OnDisconnected { get; set; }
 
         /// <summary>
         /// 请勿处理耗时操作,需立即返回。接收到客户端的数据事件
@@ -40,8 +37,6 @@ namespace Sers.CL.Socket.ThreadWait
         public Action<IDeliveryConnection, ArraySegment<byte>> OnGetFrame { private get; set; }
 
 
-        BlockingCollection<ByteData> queue = new BlockingCollection<ByteData>();
-
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         public void SendFrameAsync(Vit.Core.Util.Pipelines.ByteData data)
         {
@@ -53,18 +48,18 @@ namespace Sers.CL.Socket.ThreadWait
 
                 var bytes = data.ToBytes();
 
-                _securityManager?.Encryption(new ArraySegment<byte>(bytes, 4, bytes.Length - 4));       
+                _securityManager?.Encryption(new ArraySegment<byte>(bytes, 4, bytes.Length - 4));
 
                 socket.SendAsync(bytes.BytesToArraySegmentByte(), SocketFlags.None);
                 //socket.SendAsync(data, SocketFlags.None);
             }
             catch (Exception ex)
-            {               
+            {
                 Logger.Error(ex);
                 Close();
-            }            
+            }
         }
- 
+
 
 
         public void Close()
@@ -123,8 +118,8 @@ namespace Sers.CL.Socket.ThreadWait
         {
             this.client = client;
             socket = client.Client;
- 
-            connectTime = DateTime.Now;  
+
+            connectTime = DateTime.Now;
         }
 
 
@@ -135,11 +130,11 @@ namespace Sers.CL.Socket.ThreadWait
         public void StartBackThreadToReceiveMsg()
         {
             taskToReceiveMsg.Stop();
-             
+
             taskToReceiveMsg.threadName = "Sers.CL.Socket.ThreadWait-taskToReceiveMsg";
             taskToReceiveMsg.threadCount = 1;
             taskToReceiveMsg.Processor = TaskToReceiveMsg;
-            taskToReceiveMsg.Start();          
+            taskToReceiveMsg.Start();
         }
 
         void TaskToReceiveMsg()
@@ -148,8 +143,8 @@ namespace Sers.CL.Socket.ThreadWait
             {
                 try
                 {
-                    while (socket!=null)
-                    {       
+                    while (socket != null)
+                    {
                         OnGetFrame(this, ReadMsg());
                     }
                 }
@@ -166,7 +161,7 @@ namespace Sers.CL.Socket.ThreadWait
         /// <summary>
         /// 通信SOCKET
         /// </summary>
-        public global::System.Net.Sockets.Socket socket { get;private set; }
+        public global::System.Net.Sockets.Socket socket { get; private set; }
 
         TcpClient client;
 
@@ -198,7 +193,7 @@ namespace Sers.CL.Socket.ThreadWait
             void Receive(ArraySegment<byte> data)
             {
                 int readedCount = 0;
-                int curCount;             
+                int curCount;
                 do
                 {
                     //curCount = socket.Receive(data.Slice(readedCount, data.Count - readedCount));
@@ -206,14 +201,14 @@ namespace Sers.CL.Socket.ThreadWait
                     if (curCount == 0)
                     {
                         Logger.Error("[lith_190807_002]socket is closed.");
-                        throw new Exception("[lith_190418_002]socket is closed." );
+                        throw new Exception("[lith_190418_002]socket is closed.");
                     }
                     readedCount += curCount;
                     //var t = socket.ReceiveAsync(data.Slice(readedCount, data.Count - readedCount), SocketFlags.None);
                     //t.Wait();
                     //readedCount += t.Result;
 
-                } while (readedCount < data.Count);               
+                } while (readedCount < data.Count);
             }
 
             #endregion
@@ -222,7 +217,7 @@ namespace Sers.CL.Socket.ThreadWait
             try
             {
 
-                
+
                 //(x.1)获取 第一部分(len)  
                 Receive(bLen);
                 Int32 len = bLen.ArraySegmentByteToInt32();

+ 1 - 1
dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.ThreadWait/OrganizeClientBuilder.cs

@@ -28,7 +28,7 @@ namespace Sers.CL.Socket.ThreadWait
             delivery.host = config["host"].ConvertToString();
             delivery.port = config["port"].Convert<int>();
 
-            organizeList.Add(new OrganizeClient(delivery, config)); 
+            organizeList.Add(new OrganizeClient(delivery, config));
         }
     }
 }

+ 2 - 2
dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.ThreadWait/OrganizeServerBuilder.cs

@@ -12,7 +12,7 @@ namespace Sers.CL.Socket.ThreadWait
 {
     public class OrganizeServerBuilder : IOrganizeServerBuilder
     {
-        public void Build(List<IOrganizeServer> organizeList,JObject config)
+        public void Build(List<IOrganizeServer> organizeList, JObject config)
         {
             var delivery = new DeliveryServer();
 
@@ -27,7 +27,7 @@ namespace Sers.CL.Socket.ThreadWait
             delivery.host = config["host"].ConvertToString();
             delivery.port = config["port"].Convert<int>();
 
-            organizeList.Add(new OrganizeServer(delivery, config)); 
+            organizeList.Add(new OrganizeServer(delivery, config));
         }
     }
 }

+ 1 - 1
dotnet/Library/Sers/Sers.CL/Socket/Sers.CL.Socket.ThreadWait/Sers.CL.Socket.ThreadWait.csproj

@@ -6,7 +6,7 @@
 
     <PropertyGroup>
         <TargetFramework>netstandard2.0</TargetFramework>
-        <Version>2.1.25-temp</Version>
+        <Version>2.1.25</Version>
     </PropertyGroup>
 
     <PropertyGroup>

+ 13 - 12
dotnet/Library/Sers/Sers.CL/Test/CommunicationManage/CmClient/ProgramQps.cs

@@ -1,11 +1,12 @@
 using System;
 using System.Threading;
-using System.Threading.Tasks;
+
 using CLClient.Statistics;
+
 using Sers.Core.CL.CommunicationManage;
+
 using Vit.Core.Module.Log;
 using Vit.Core.Util.Pipelines;
-using Vit.Core.Util.Threading;
 
 namespace CLClient
 {
@@ -21,7 +22,7 @@ namespace CLClient
             qpsInfo.Start("Msg");
 
 
-            for (int i = Vit.Core.Util.ConfigurationManager.Appsettings.json.GetByPath<int>("PressureTest.clientCount"); i >0; i--)
+            for (int i = Vit.Core.Util.ConfigurationManager.Appsettings.json.GetByPath<int>("PressureTest.clientCount"); i > 0; i--)
             {
                 StartThreadSendMessage();
             }
@@ -29,7 +30,7 @@ namespace CLClient
             Sers.Core.Module.App.SersApplication.OnStart();
 
             while (true)
-            {              
+            {
                 Thread.Sleep(5000);
             }
 
@@ -37,28 +38,28 @@ namespace CLClient
 
 
 
-      
+
         static void StartThreadSendMessage()
         {
 
             CommunicationManageClient cm = new CommunicationManageClient();
-         
+
 
             cm.Conn_OnDisconnected = (conn) =>
             {
-                Logger.Info("Conn_OnDisconnected");       
+                Logger.Info("Conn_OnDisconnected");
 
                 Sers.Core.Module.App.SersApplication.OnStop();
             };
 
-         
 
-            cm.conn_OnGetMessage = (conn,msg) => 
+
+            cm.conn_OnGetMessage = (conn, msg) =>
             {
                 //Task.Run(() =>
                 //{
-                    qpsInfo.IncrementRequest();
-                    cm.SendMessageAsync(new ByteData(msg));
+                qpsInfo.IncrementRequest();
+                cm.SendMessageAsync(new ByteData(msg));
                 //});
             };
 
@@ -126,7 +127,7 @@ namespace CLClient
             }
 
 
- 
+
 
 
 

+ 8 - 7
dotnet/Library/Sers/Sers.CL/Test/CommunicationManage/CmClient/Statistics/StatisticsQpsInfo.cs

@@ -24,7 +24,8 @@ namespace CLClient.Statistics
             startTime = DateTime.Now;
             Console.WriteLine("¿ªÊ¼");
 
-            Task.Run(() => {
+            Task.Run(() =>
+            {
 
                 while (!finished)
                 {
@@ -81,23 +82,23 @@ namespace CLClient.Statistics
 
                 //sum
                 var ms = (curTime - startTime.Value).TotalMilliseconds;
-                d =  curCount / ms * 1000;
-                msg += $",qps:{ d.ToString("0.00") }";
+                d = curCount / ms * 1000;
+                msg += $",qps:{d.ToString("0.00")}";
 
                 ms = 1.0 * curRequestTicks / TimeSpan.TicksPerMillisecond;
                 d = (curCount <= 0 ? 0 : ms / curCount);
-                msg += $",ms/req:{ d.ToString("0.00") }";
+                msg += $",ms/req:{d.ToString("0.00")}";
 
 
                 //cur
-                msg += $",------Cur";                
+                msg += $",------Cur";
                 msg += $",ReqCount: {curCount}";
                 ms = (curTime - lastTime).TotalMilliseconds;
                 d = (curCount - lastCount) / ms * 1000;
-                msg += $",qps:{ d.ToString("0.00")  }";
+                msg += $",qps:{d.ToString("0.00")}";
                 ms = 1.0 * (curRequestTicks - lastRequestTicks) / TimeSpan.TicksPerMillisecond;
                 d = (curCount <= lastCount ? 0 : ms / (curCount - lastCount));
-                msg += $",ms/req:{ d.ToString("0.00") }";
+                msg += $",ms/req:{d.ToString("0.00")}";
 
 
                 lastRequestTicks = curRequestTicks;

+ 5 - 2
dotnet/Library/Sers/Sers.CL/Test/CommunicationManage/CmServer/Program.cs

@@ -1,8 +1,11 @@
 using System;
 using System.Threading;
+
 using CLServer.Statistics;
+
 using Sers.Core.CL.CommunicationManage;
 using Sers.Core.CL.MessageOrganize;
+
 using Vit.Core.Module.Log;
 using Vit.Core.Util.Pipelines;
 
@@ -21,7 +24,7 @@ namespace CLServer
             qpsInfo.Start("Msg");
 
             CommunicationManageServer cm = new CommunicationManageServer();
-           
+
 
             cm.conn_OnGetMessage = (conn, msg) =>
             {
@@ -30,7 +33,7 @@ namespace CLServer
             };
 
 
-            cm.conn_OnGetRequest = (IOrganizeConnection  conn, Object sender, ArraySegment<byte> apiRequest, Action<object, Vit.Core.Util.Pipelines.ByteData> callback) =>
+            cm.conn_OnGetRequest = (IOrganizeConnection conn, Object sender, ArraySegment<byte> apiRequest, Action<object, Vit.Core.Util.Pipelines.ByteData> callback) =>
             {
                 qpsInfo.IncrementRequest();
                 callback(sender, new ByteData(apiRequest));

+ 8 - 7
dotnet/Library/Sers/Sers.CL/Test/CommunicationManage/CmServer/Statistics/StatisticsQpsInfo.cs

@@ -24,7 +24,8 @@ namespace CLServer.Statistics
             startTime = DateTime.Now;
             Console.WriteLine("¿ªÊ¼");
 
-            Task.Run(() => {
+            Task.Run(() =>
+            {
 
                 while (!finished)
                 {
@@ -81,23 +82,23 @@ namespace CLServer.Statistics
 
                 //sum
                 var ms = (curTime - startTime.Value).TotalMilliseconds;
-                d =  curCount / ms * 1000;
-                msg += $",qps:{ d.ToString("0.00") }";
+                d = curCount / ms * 1000;
+                msg += $",qps:{d.ToString("0.00")}";
 
                 ms = 1.0 * curRequestTicks / TimeSpan.TicksPerMillisecond;
                 d = (curCount <= 0 ? 0 : ms / curCount);
-                msg += $",ms/req:{ d.ToString("0.00") }";
+                msg += $",ms/req:{d.ToString("0.00")}";
 
 
                 //cur
-                msg += $",------Cur";                
+                msg += $",------Cur";
                 msg += $",ReqCount: {curCount}";
                 ms = (curTime - lastTime).TotalMilliseconds;
                 d = (curCount - lastCount) / ms * 1000;
-                msg += $",qps:{ d.ToString("0.00")  }";
+                msg += $",qps:{d.ToString("0.00")}";
                 ms = 1.0 * (curRequestTicks - lastRequestTicks) / TimeSpan.TicksPerMillisecond;
                 d = (curCount <= lastCount ? 0 : ms / (curCount - lastCount));
-                msg += $",ms/req:{ d.ToString("0.00") }";
+                msg += $",ms/req:{d.ToString("0.00")}";
 
 
                 lastRequestTicks = curRequestTicks;

+ 13 - 13
dotnet/Library/Sers/Sers.CL/Test/MessageDelivery/DeliveryClient/Program.cs

@@ -1,11 +1,11 @@
-using CLServer.Statistics;
-using Sers.Core.CL.MessageDelivery;
-using System;
-using System.Collections.Generic;
+using System;
 using System.Threading;
-using System.Threading.Tasks;
+
+using CLServer.Statistics;
+
+using Sers.Core.CL.MessageDelivery;
+
 using Vit.Core.Module.Log;
-using Vit.Core.Util.Threading;
 
 namespace DeliveryTest
 {
@@ -94,7 +94,7 @@ namespace DeliveryTest
 
             //client = new Sers.CL.Socket.ThreadWait.DeliveryClient();
 
-       
+
 
             //client = new Sers.CL.WebSocket.DeliveryClient();
             //client = new Sers.CL.ClrZmq.ThreadWait.DeliveryClient();
@@ -108,15 +108,15 @@ namespace DeliveryTest
            {
                //Task.Run(() =>
                //{
-                   qpsInfo.IncrementRequest();
+               qpsInfo.IncrementRequest();
 
-                   //Thread.Sleep(1);
+               //Thread.Sleep(1);
 
-                   //data[0]++;
-                   //data[1] = 10;                 
+               //data[0]++;
+               //data[1] = 10;                 
 
-                   var byteData = new Vit.Core.Util.Pipelines.ByteData(data);
-                   conn.SendFrameAsync(byteData);
+               var byteData = new Vit.Core.Util.Pipelines.ByteData(data);
+               conn.SendFrameAsync(byteData);
                //});
 
            };

+ 8 - 7
dotnet/Library/Sers/Sers.CL/Test/MessageDelivery/DeliveryClient/Statistics/StatisticsQpsInfo.cs

@@ -24,7 +24,8 @@ namespace CLServer.Statistics
             startTime = DateTime.Now;
             Console.WriteLine("¿ªÊ¼");
 
-            Task.Run(() => {
+            Task.Run(() =>
+            {
 
                 while (!finished)
                 {
@@ -81,23 +82,23 @@ namespace CLServer.Statistics
 
                 //sum
                 var ms = (curTime - startTime.Value).TotalMilliseconds;
-                d =  curCount / ms * 1000;
-                msg += $",qps:{ d.ToString("0.00") }";
+                d = curCount / ms * 1000;
+                msg += $",qps:{d.ToString("0.00")}";
 
                 ms = 1.0 * curRequestTicks / TimeSpan.TicksPerMillisecond;
                 d = (curCount <= 0 ? 0 : ms / curCount);
-                msg += $",ms/req:{ d.ToString("0.00") }";
+                msg += $",ms/req:{d.ToString("0.00")}";
 
 
                 //cur
-                msg += $",------Cur";                
+                msg += $",------Cur";
                 msg += $",ReqCount: {curCount}";
                 ms = (curTime - lastTime).TotalMilliseconds;
                 d = (curCount - lastCount) / ms * 1000;
-                msg += $",qps:{ d.ToString("0.00")  }";
+                msg += $",qps:{d.ToString("0.00")}";
                 ms = 1.0 * (curRequestTicks - lastRequestTicks) / TimeSpan.TicksPerMillisecond;
                 d = (curCount <= lastCount ? 0 : ms / (curCount - lastCount));
-                msg += $",ms/req:{ d.ToString("0.00") }";
+                msg += $",ms/req:{d.ToString("0.00")}";
 
 
                 lastRequestTicks = curRequestTicks;

+ 8 - 6
dotnet/Library/Sers/Sers.CL/Test/MessageDelivery/DeliveryServer/Program.cs

@@ -1,8 +1,10 @@
-using CLServer.Statistics;
-using Sers.Core.CL.MessageDelivery;
-using System;
+using System;
 using System.Threading;
-using System.Threading.Tasks;
+
+using CLServer.Statistics;
+
+using Sers.Core.CL.MessageDelivery;
+
 using Vit.Core.Module.Log;
 
 namespace DeliveryTest
@@ -55,9 +57,9 @@ namespace DeliveryTest
 
                 server = delivery;
             }
-          
+
             //server = new Sers.CL.Socket.ThreadWait.DeliveryServer();
-       
+
 
             //server = new Sers.CL.WebSocket.DeliveryServer();
             //server = new Sers.CL.ClrZmq.ThreadWait.DeliveryServer();

+ 8 - 7
dotnet/Library/Sers/Sers.CL/Test/MessageDelivery/DeliveryServer/Statistics/StatisticsQpsInfo.cs

@@ -24,7 +24,8 @@ namespace CLServer.Statistics
             startTime = DateTime.Now;
             Console.WriteLine("¿ªÊ¼");
 
-            Task.Run(() => {
+            Task.Run(() =>
+            {
 
                 while (!finished)
                 {
@@ -81,23 +82,23 @@ namespace CLServer.Statistics
 
                 //sum
                 var ms = (curTime - startTime.Value).TotalMilliseconds;
-                d =  curCount / ms * 1000;
-                msg += $",qps:{ d.ToString("0.00") }";
+                d = curCount / ms * 1000;
+                msg += $",qps:{d.ToString("0.00")}";
 
                 ms = 1.0 * curRequestTicks / TimeSpan.TicksPerMillisecond;
                 d = (curCount <= 0 ? 0 : ms / curCount);
-                msg += $",ms/req:{ d.ToString("0.00") }";
+                msg += $",ms/req:{d.ToString("0.00")}";
 
 
                 //cur
-                msg += $",------Cur";                
+                msg += $",------Cur";
                 msg += $",ReqCount: {curCount}";
                 ms = (curTime - lastTime).TotalMilliseconds;
                 d = (curCount - lastCount) / ms * 1000;
-                msg += $",qps:{ d.ToString("0.00")  }";
+                msg += $",qps:{d.ToString("0.00")}";
                 ms = 1.0 * (curRequestTicks - lastRequestTicks) / TimeSpan.TicksPerMillisecond;
                 d = (curCount <= lastCount ? 0 : ms / (curCount - lastCount));
-                msg += $",ms/req:{ d.ToString("0.00") }";
+                msg += $",ms/req:{d.ToString("0.00")}";
 
 
                 lastRequestTicks = curRequestTicks;

+ 10 - 10
dotnet/Library/Sers/Sers.CL/Test/MessageDelivery/DeliveryTest/Program.cs

@@ -1,6 +1,6 @@
 using System;
-using System.Collections.Generic;
 using System.Threading;
+
 using Vit.Core.Module.Log;
 
 namespace DeliveryTest
@@ -8,7 +8,7 @@ namespace DeliveryTest
     class Program
     {
 
-   
+
         static void Main(string[] args)
         {
             Logger.PrintToConsole = true;
@@ -26,7 +26,7 @@ namespace DeliveryTest
 
 
 
-      
+
         static void StartServer()
         {
 
@@ -36,7 +36,7 @@ namespace DeliveryTest
             //var server = new Sers.CL.Zmq.FullDuplex.DeliveryServer();
             var server = new Sers.CL.Ipc.NamedPipe.DeliveryServer();
 
-            server.Conn_OnConnected = (conn) => 
+            server.Conn_OnConnected = (conn) =>
             {
                 conn.OnGetFrame = (conn_, data) =>
                 {
@@ -47,15 +47,15 @@ namespace DeliveryTest
                     conn_.SendFrameAsync(byteData);
                 };
             };
-           
+
 
             server.Start();
 
         }
 
-        static Vit.Core.Util.Pipelines.ByteData staticByteData => new Vit.Core.Util.Pipelines.ByteData( new ArraySegment<byte>(new byte[] { 0, 1, 2, 3 }));
+        static Vit.Core.Util.Pipelines.ByteData staticByteData => new Vit.Core.Util.Pipelines.ByteData(new ArraySegment<byte>(new byte[] { 0, 1, 2, 3 }));
+
 
- 
         static void StartClient()
         {
             //var client = new Sers.CL.WebSocket.DeliveryClient();
@@ -73,10 +73,10 @@ namespace DeliveryTest
                 conn.SendFrameAsync(byteData);
             };
 
-            var connected = client.Connect() ;
+            var connected = client.Connect();
+
+            Thread.Sleep(1000);
 
-            Thread.Sleep(1000);           
-         
             client.conn.SendFrameAsync(staticByteData);
 
 

+ 9 - 7
dotnet/Library/Sers/Sers.CL/WebSocket/Sers.CL.WebSocket/DeliveryClient.cs

@@ -3,20 +3,22 @@
 using System;
 using System.Net.WebSockets;
 using System.Threading;
+
 using Sers.Core.CL.MessageDelivery;
+
 using Vit.Core.Module.Log;
 using Vit.Extensions.Object_Extensions;
 
 namespace Sers.CL.WebSocket
 {
-    public class DeliveryClient: IDeliveryClient
+    public class DeliveryClient : IDeliveryClient
     {
 
 
         DeliveryClient_Connection _conn = new DeliveryClient_Connection();
         public IDeliveryConnection conn => _conn;
 
-        public Action<IDeliveryConnection, ArraySegment<byte>> Conn_OnGetFrame { set { _conn.OnGetFrame = value; }  }
+        public Action<IDeliveryConnection, ArraySegment<byte>> Conn_OnGetFrame { set { _conn.OnGetFrame = value; } }
 
 
         public Action<IDeliveryConnection> Conn_OnDisconnected { set => _conn.Conn_OnDisconnected = value; }
@@ -57,7 +59,7 @@ namespace Sers.CL.WebSocket
 
 
                 _webSocket.ConnectAsync(new Uri(host), new CancellationToken()).GetAwaiter().GetResult();
-                _conn.Init(_webSocket);                
+                _conn.Init(_webSocket);
 
                 _conn.StartBackThreadToReceiveMsg();
 
@@ -71,7 +73,7 @@ namespace Sers.CL.WebSocket
             return false;
         }
 
-    
+
         public void Close()
         {
             if (null == _conn) return;
@@ -79,9 +81,9 @@ namespace Sers.CL.WebSocket
             _conn = null;
             conn.Close();
         }
- 
- 
- 
+
+
+
 
 
 

+ 10 - 11
dotnet/Library/Sers/Sers.CL/WebSocket/Sers.CL.WebSocket/DeliveryClient_Connection.cs

@@ -7,7 +7,6 @@ using Sers.Core.CL.MessageDelivery;
 using Vit.Core.Module.Log;
 using Vit.Core.Util.Pipelines;
 using Vit.Core.Util.Threading.Worker;
-using Vit.Extensions;
 using Vit.Extensions.Json_Extensions;
 
 namespace Sers.CL.WebSocket
@@ -53,8 +52,8 @@ namespace Sers.CL.WebSocket
             {
                 Logger.Error(ex);
                 Close();
-            }       
-   
+            }
+
         }
 
         CancellationToken _cancellation = new CancellationToken();
@@ -70,10 +69,10 @@ namespace Sers.CL.WebSocket
 
             try
             {
-                socket_.CloseAsync(WebSocketCloseStatus.NormalClosure,"", _cancellation).GetAwaiter().GetResult();
+                socket_.CloseAsync(WebSocketCloseStatus.NormalClosure, "", _cancellation).GetAwaiter().GetResult();
                 //socket_.Abort();
 
-                socket_.Dispose();     
+                socket_.Dispose();
             }
             catch (Exception ex)
             {
@@ -92,13 +91,13 @@ namespace Sers.CL.WebSocket
         }
         public void Init(ClientWebSocket socket)
         {
-            this.socket = socket;          
+            this.socket = socket;
         }
- 
+
         /// <summary>
         /// 通信SOCKET
         /// </summary>
-        public ClientWebSocket socket { get;private set; }
+        public ClientWebSocket socket { get; private set; }
 
 
 
@@ -140,9 +139,9 @@ namespace Sers.CL.WebSocket
                 {
                     while (socket != null)
                     {
-                        var data =  new byte[receiveBufferSize];
-                        var result= socket.ReceiveAsync(new ArraySegment<byte>(data), _cancellation).GetAwaiter().GetResult();                        
-                        AppendData(new ArraySegment<byte>(data,0, result.Count));
+                        var data = new byte[receiveBufferSize];
+                        var result = socket.ReceiveAsync(new ArraySegment<byte>(data), _cancellation).GetAwaiter().GetResult();
+                        AppendData(new ArraySegment<byte>(data, 0, result.Count));
                     }
                 }
                 catch (Exception ex) when (!(ex.GetBaseException() is ThreadInterruptedException))

+ 7 - 7
dotnet/Library/Sers/Sers.CL/WebSocket/Sers.CL.WebSocket/DeliveryServer_Connection.cs

@@ -49,9 +49,9 @@ namespace Sers.CL.WebSocket
             {
                 Logger.Error(ex);
                 Close();
-            }         
+            }
         }
-     
+
 
         public void Close()
         {
@@ -60,11 +60,11 @@ namespace Sers.CL.WebSocket
             state = DeliveryConnState.closed;
 
             var socket_ = socket;
-            socket = null;          
+            socket = null;
 
             try
             {
-                socket_.Close();     
+                socket_.Close();
             }
             catch (Exception ex)
             {
@@ -83,13 +83,13 @@ namespace Sers.CL.WebSocket
         }
         public void Init(IWebSocketConnection socket)
         {
-            this.socket = socket;          
+            this.socket = socket;
         }
- 
+
         /// <summary>
         /// 通信SOCKET
         /// </summary>
-        public IWebSocketConnection socket { get;private set; }
+        public IWebSocketConnection socket { get; private set; }
 
 
 

+ 0 - 1
dotnet/Library/Sers/Sers.CL/WebSocket/Sers.CL.WebSocket/OrganizeClientBuilder.cs

@@ -5,7 +5,6 @@ using Newtonsoft.Json.Linq;
 using Sers.Core.CL.MessageOrganize;
 using Sers.Core.CL.MessageOrganize.DefaultOrganize;
 
-using Vit.Extensions;
 using Vit.Extensions.Newtonsoft_Extensions;
 
 namespace Sers.CL.WebSocket

+ 0 - 1
dotnet/Library/Sers/Sers.CL/WebSocket/Sers.CL.WebSocket/OrganizeServerBuilder.cs

@@ -5,7 +5,6 @@ using Newtonsoft.Json.Linq;
 using Sers.Core.CL.MessageOrganize;
 using Sers.Core.CL.MessageOrganize.DefaultOrganize;
 
-using Vit.Extensions;
 using Vit.Extensions.Newtonsoft_Extensions;
 
 namespace Sers.CL.WebSocket

+ 1 - 1
dotnet/Library/Sers/Sers.CL/WebSocket/Sers.CL.WebSocket/Sers.CL.WebSocket.csproj

@@ -6,7 +6,7 @@
 
     <PropertyGroup>
         <TargetFramework>netstandard2.0</TargetFramework>
-        <Version>2.1.25-temp</Version>
+        <Version>2.1.25</Version>
     </PropertyGroup>
 
     <PropertyGroup>

+ 4 - 4
dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/DeliveryClient.cs

@@ -26,10 +26,10 @@ namespace Sers.CL.Zmq.FullDuplex
 
 
 
-        public Action<IDeliveryConnection, ArraySegment<byte>> Conn_OnGetFrame {  set => _conn.OnGetFrame = value; }
+        public Action<IDeliveryConnection, ArraySegment<byte>> Conn_OnGetFrame { set => _conn.OnGetFrame = value; }
+
+        public Action<IDeliveryConnection> Conn_OnDisconnected { set => _conn.Conn_OnDisconnected = value; }
 
-        public Action<IDeliveryConnection> Conn_OnDisconnected {  set => _conn.Conn_OnDisconnected = value; }
- 
 
 
         /// <summary>
@@ -63,7 +63,7 @@ namespace Sers.CL.Zmq.FullDuplex
 
                 //(x.4) Start stream               
                 stream.OnReceiveMessage = OnReceiveMessage;
-                stream.BeforeStop = () => 
+                stream.BeforeStop = () =>
                 {
                     SendCloseSignal();
                     _conn.Close();

+ 7 - 8
dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/DeliveryConnection.cs

@@ -1,5 +1,4 @@
 using System;
-using System.Collections.Generic;
 
 using Sers.Core.CL.MessageDelivery;
 
@@ -9,7 +8,7 @@ using Vit.Extensions.Json_Extensions;
 namespace Sers.CL.Zmq.FullDuplex
 {
     public class DeliveryConnection : IDeliveryConnection
-    {       
+    {
         ~DeliveryConnection()
         {
             Close();
@@ -28,13 +27,13 @@ namespace Sers.CL.Zmq.FullDuplex
         {
             identity <<= 1;
             identityOfWriter = identity.Int64ToBytes();
-            identityOfReader = (++ identity ).Int64ToBytes();
+            identityOfReader = (++identity).Int64ToBytes();
         }
 
         internal byte[] identityOfReader { get; set; }
         internal byte[] identityOfWriter { get; set; }
 
- 
+
         Action<IDeliveryConnection, ArraySegment<byte>> _OnGetFrame;
         public Action<IDeliveryConnection, ArraySegment<byte>> OnGetFrame
         {
@@ -57,17 +56,17 @@ namespace Sers.CL.Zmq.FullDuplex
         {
             var bytes = data.ToBytes();
 
-            _securityManager?.Encryption(bytes.BytesToArraySegmentByte()); 
+            _securityManager?.Encryption(bytes.BytesToArraySegmentByte());
 
             OnSendFrameAsync(this, bytes);
         }
-        
+
 
         public Action<IDeliveryConnection> Conn_OnDisconnected { get; set; }
 
         public void Close()
-        {             
-            state = DeliveryConnState.closed;             
+        {
+            state = DeliveryConnState.closed;
             try
             {
                 Conn_OnDisconnected?.Invoke(this);

+ 10 - 10
dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/DeliveryServer.cs

@@ -18,7 +18,7 @@ namespace Sers.CL.Zmq.FullDuplex
         public Sers.Core.Util.StreamSecurity.SecurityManager securityManager;
 
         public Action<IDeliveryConnection> Conn_OnDisconnected { private get; set; }
-        public Action<IDeliveryConnection> Conn_OnConnected { private get; set; } 
+        public Action<IDeliveryConnection> Conn_OnConnected { private get; set; }
 
         /// <summary>
         ///  connGuid -> conn
@@ -35,7 +35,7 @@ namespace Sers.CL.Zmq.FullDuplex
         public string endpoint = "tcp://*:4504";
         ZSocket socketRouter;
         SocketStream stream = new SocketStream();
- 
+
         #region Start
 
         /// <summary>
@@ -54,13 +54,13 @@ namespace Sers.CL.Zmq.FullDuplex
 
                 //(x.2) create zmq socketWriter
                 var socketWriter = new ZSocket(ZSocketType.DEALER);
-                socketWriter.Identity = ((long) 0).Int64ToBytes();
+                socketWriter.Identity = ((long)0).Int64ToBytes();
                 socketWriter.Connect(endpoint.Replace("*", "127.0.0.1"));
 
 
                 //(x.3) Start stream
                 stream.OnReceiveMessage = OnReceiveMessage;
-                stream.BeforeStop = () => 
+                stream.BeforeStop = () =>
                 {
                     Logger.Info("[CL.DeliveryServer] Zmq.FullDuplex,stoping");
 
@@ -71,7 +71,7 @@ namespace Sers.CL.Zmq.FullDuplex
                     //以防 关闭命令 没有发送出去
                     Thread.Sleep(100);
                 };
-                stream.AfterStop = () => {            Logger.Info("[CL.DeliveryServer] Zmq.FullDuplex,stoped");    };
+                stream.AfterStop = () => { Logger.Info("[CL.DeliveryServer] Zmq.FullDuplex,stoped"); };
                 stream.Start(socketRouter, socketWriter);
                 Logger.Info("[CL.DeliveryServer] Zmq.FullDuplex,started");
                 return true;
@@ -87,7 +87,7 @@ namespace Sers.CL.Zmq.FullDuplex
         {
             if (null == msg || msg.Count < 2) return;
 
-            long identityOfWriter  = msg[0].BytesToInt64();
+            long identityOfWriter = msg[0].BytesToInt64();
 
             if (identityOfWriter != 0)
             {
@@ -143,13 +143,13 @@ namespace Sers.CL.Zmq.FullDuplex
                 msg.RemoveAt(0);
                 socketRouter.SendMessage(msg.ToArray());
                 #endregion
-            }   
+            }
 
         }
 
-        void SendMessageAsync(DeliveryConnection conn,byte[] data)
+        void SendMessageAsync(DeliveryConnection conn, byte[] data)
         {
-            stream.SendMessageAsync( conn.identityOfReader, data  );
+            stream.SendMessageAsync(conn.identityOfReader, data);
         }
 
         void SendCloseSignal(DeliveryConnection conn)
@@ -221,7 +221,7 @@ namespace Sers.CL.Zmq.FullDuplex
 
 
 
-      
+
 
 
 

+ 1 - 1
dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/OrganizeServerBuilder.cs

@@ -27,6 +27,6 @@ namespace Sers.CL.Zmq.FullDuplex
 
             organizeList.Add(new OrganizeServer(delivery, config));
         }
- 
+
     }
 }

+ 5 - 5
dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/SocketStream.cs

@@ -1,10 +1,10 @@
-using Sers.CL.Zmq.FullDuplex.Zmq;
-
-using System;
+using System;
 using System.Collections.Concurrent;
 using System.Collections.Generic;
 using System.Threading;
 
+using Sers.CL.Zmq.FullDuplex.Zmq;
+
 using Vit.Core.Module.Log;
 using Vit.Core.Util.Threading.Worker;
 
@@ -15,7 +15,7 @@ namespace Sers.CL.Zmq.FullDuplex
         ZSocket socketReader;
         ZSocket socketWriter;
 
- 
+
 
         public Action<List<byte[]>> OnReceiveMessage;
 
@@ -97,7 +97,7 @@ namespace Sers.CL.Zmq.FullDuplex
             {
                 Logger.Error(ex);
             }
-            
+
         }
 
 

+ 38 - 38
dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/Zmq/DispoIntPtr.cs

@@ -3,49 +3,49 @@
     using System;
     using System.Runtime.InteropServices;
 
-    internal sealed   class DispoIntPtr : IDisposable
-	{
-   
+    internal sealed class DispoIntPtr : IDisposable
+    {
+
         public DispoIntPtr(int size)
         {
             Ptr = Marshal.AllocHGlobal(size);
-            isAllocated = true; 
+            isAllocated = true;
         }
 
-        private bool isAllocated;	 
-
-		public IntPtr Ptr{  get;    private set; }
-
-
-
-		~DispoIntPtr()
-		{
-			Dispose(false);
-		}
-
-		public void Dispose()
-		{
-			Dispose(true);
-			GC.SuppressFinalize(this);
-		}
-
-		void Dispose(bool disposing)
-		{
-			// TODO: instance ThreadStatic && do ( o == null ? return : ( lock(o, ms), check threadId, .. ) ) 
-			IntPtr handle = Ptr;
-			if (handle != IntPtr.Zero)
-			{
-				if (isAllocated)
-				{
-					Marshal.FreeHGlobal(handle);
-					isAllocated = false;
-				}
-                Ptr = IntPtr.Zero;
-			}
-		}
-
-
-   
+        private bool isAllocated;
+
+        public IntPtr Ptr { get; private set; }
+
+
+
+        ~DispoIntPtr()
+        {
+            Dispose(false);
+        }
+
+        public void Dispose()
+        {
+            Dispose(true);
+            GC.SuppressFinalize(this);
+        }
+
+        void Dispose(bool disposing)
+        {
+            // TODO: instance ThreadStatic && do ( o == null ? return : ( lock(o, ms), check threadId, .. ) ) 
+            IntPtr handle = Ptr;
+            if (handle != IntPtr.Zero)
+            {
+                if (isAllocated)
+                {
+                    Marshal.FreeHGlobal(handle);
+                    isAllocated = false;
+                }
+                Ptr = IntPtr.Zero;
+            }
+        }
+
+
+
 
 
     }

+ 294 - 296
dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/Zmq/Platform.cs

@@ -1,14 +1,12 @@
 namespace Sers.CL.Zmq.FullDuplex.Zmq
 {
-	using System;
-	using System.Collections.Generic;
-    using System.Diagnostics;
+    using System;
+    using System.Collections.Generic;
     using System.IO;
-	using System.Linq;
-	using System.Reflection;
-	using System.Runtime.InteropServices;
+    using System.Linq;
+    using System.Reflection;
 
-	/* Common CLR type System.Runtime.InteropServices.ImageFileMachine *
+    /* Common CLR type System.Runtime.InteropServices.ImageFileMachine *
 	public enum ImageFileMachine
 	{
 		i386    = 0x014C,
@@ -18,81 +16,81 @@ namespace Sers.CL.Zmq.FullDuplex.Zmq
 		
 	} /**/
 
-	public enum PlatformKind : int
-	{
-		__Internal = 0,
-		Posix,
-		Win32,
-	}
+    public enum PlatformKind : int
+    {
+        __Internal = 0,
+        Posix,
+        Win32,
+    }
 
-	public enum PlatformName : int
-	{
-		__Internal = 0,
-		Posix,
-		Windows,
-		MacOSX,
-	}
+    public enum PlatformName : int
+    {
+        __Internal = 0,
+        Posix,
+        Windows,
+        MacOSX,
+    }
 
-	public static partial class Platform
-	{
-		public static readonly string[] Compilers = new string[] {
-			"msvc2008",
-			"msvc2010",
-			"msvc2012",
-			"msvc2013",
-			"msvc2015",
-			"gcc3",
-			"gcc4",
-			"gcc5",
-			"mingw32",
-		};
+    public static partial class Platform
+    {
+        public static readonly string[] Compilers = new string[] {
+            "msvc2008",
+            "msvc2010",
+            "msvc2012",
+            "msvc2013",
+            "msvc2015",
+            "gcc3",
+            "gcc4",
+            "gcc5",
+            "mingw32",
+        };
 
-		public static readonly string LibraryName;
+        public static readonly string LibraryName;
 
-		// public static readonly string LibraryFileExtension;
+        // public static readonly string LibraryFileExtension;
 
-		public static readonly string[] LibraryPaths;
+        public static readonly string[] LibraryPaths;
 
-		//public delegate UnmanagedLibrary LoadUnmanagedLibraryDelegate(string libraryName);
-		//public static readonly LoadUnmanagedLibraryDelegate LoadUnmanagedLibrary;
+        //public delegate UnmanagedLibrary LoadUnmanagedLibraryDelegate(string libraryName);
+        //public static readonly LoadUnmanagedLibraryDelegate LoadUnmanagedLibrary;
 
-		//public delegate SafeLibraryHandle OpenHandleDelegate(string filename);
-		//public static readonly OpenHandleDelegate OpenHandle;
+        //public delegate SafeLibraryHandle OpenHandleDelegate(string filename);
+        //public static readonly OpenHandleDelegate OpenHandle;
 
-		//public delegate IntPtr LoadProcedureDelegate(SafeLibraryHandle handle, string functionName);
-		//public static readonly LoadProcedureDelegate LoadProcedure;
+        //public delegate IntPtr LoadProcedureDelegate(SafeLibraryHandle handle, string functionName);
+        //public static readonly LoadProcedureDelegate LoadProcedure;
 
-		public delegate bool ReleaseHandleDelegate(IntPtr handle);
-		public static readonly ReleaseHandleDelegate ReleaseHandle;
+        public delegate bool ReleaseHandleDelegate(IntPtr handle);
+        public static readonly ReleaseHandleDelegate ReleaseHandle;
 
-		public delegate Exception GetLastLibraryErrorDelegate();
-		public static readonly GetLastLibraryErrorDelegate GetLastLibraryError;
+        public delegate Exception GetLastLibraryErrorDelegate();
+        public static readonly GetLastLibraryErrorDelegate GetLastLibraryError;
 
-		public static readonly bool Is__Internal;
+        public static readonly bool Is__Internal;
 
-		public static readonly PlatformKind Kind;
+        public static readonly PlatformKind Kind;
 
-		public static readonly PlatformName Name;
+        public static readonly PlatformName Name;
 
-		public static readonly ImageFileMachine Architecture;
+        public static readonly ImageFileMachine Architecture;
 
-		public static readonly string Compiler;
+        public static readonly string Compiler;
 
-		static Platform()
-		{
-			PortableExecutableKinds peKinds;
-			typeof(object).Module.GetPEKind(out peKinds, out Architecture);
+        static Platform()
+        {
+            PortableExecutableKinds peKinds;
+            typeof(object).Module.GetPEKind(out peKinds, out Architecture);
 
-			// Version osVersion;
-			switch (Environment.OSVersion.Platform)
-			{
-				case PlatformID.Win32Windows: // Win9x supported?
-				case PlatformID.Win32S: // Win16 NTVDM on Win x86?
-				case PlatformID.Win32NT: // Windows NT
-					Kind = PlatformKind.Win32;
-					Name = PlatformName.Windows;
+            // Version osVersion;
+            switch (Environment.OSVersion.Platform)
+            {
+                case PlatformID.Win32Windows: // Win9x supported?
+                case PlatformID.Win32S: // Win16 NTVDM on Win x86?
+                case PlatformID.Win32NT: // Windows NT
+                    Kind = PlatformKind.Win32;
+                    Name = PlatformName.Windows;
 
-					/* osVersion = Environment.OSVersion.Version;
+                    /* osVersion = Environment.OSVersion.Version;
 					if (osVersion.Major <= 4) {
 						// WinNT 4
 					} else if (osVersion.Major <= 5) {
@@ -105,39 +103,39 @@ namespace Sers.CL.Zmq.FullDuplex.Zmq
 						// info: technet .. msdn .. microsoft research
 
 					} */
-					break;
+                    break;
 
-				case PlatformID.WinCE:
-					// case PlatformID.Xbox:
-					Kind = PlatformKind.Win32;
-					Name = PlatformName.Windows;
-					break;
+                case PlatformID.WinCE:
+                    // case PlatformID.Xbox:
+                    Kind = PlatformKind.Win32;
+                    Name = PlatformName.Windows;
+                    break;
 
-				case PlatformID.Unix:
-					// note: current Mono versions still indicate Unix for Mac OS X
-					Kind = PlatformKind.Posix;
-					Name = PlatformName.Posix;
-					break;
+                case PlatformID.Unix:
+                    // note: current Mono versions still indicate Unix for Mac OS X
+                    Kind = PlatformKind.Posix;
+                    Name = PlatformName.Posix;
+                    break;
 
-				case PlatformID.MacOSX:
-					Kind = PlatformKind.Posix;
-					Name = PlatformName.MacOSX;
-					break;
+                case PlatformID.MacOSX:
+                    Kind = PlatformKind.Posix;
+                    Name = PlatformName.MacOSX;
+                    break;
 
-				default:
-					if ((int)Environment.OSVersion.Platform == 128)
-					{
-						// Mono formerly used 128 for MacOSX
-						Kind = PlatformKind.Posix;
-						Name = PlatformName.MacOSX;
-					}
+                default:
+                    if ((int)Environment.OSVersion.Platform == 128)
+                    {
+                        // Mono formerly used 128 for MacOSX
+                        Kind = PlatformKind.Posix;
+                        Name = PlatformName.MacOSX;
+                    }
 
-					break;
-			}
+                    break;
+            }
 
-			// TODO: Detect and distinguish available Compilers and Runtimes
+            // TODO: Detect and distinguish available Compilers and Runtimes
 
-			/* switch (Kind) {
+            /* switch (Kind) {
 
 			case PlatformKind.Windows:
 				LibraryFileNameFormat = Platform.Windows.LibraryFileNameFormat;
@@ -160,212 +158,212 @@ namespace Sers.CL.Zmq.FullDuplex.Zmq
 				throw new PlatformNotSupportedException ();
 			} */
 
-			IsMono = Type.GetType("Mono.Runtime") != null;
-
-			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
-			IsMonoTouch = assemblies.Any(a => a.GetName().Name.Equals("MonoTouch", StringComparison.InvariantCultureIgnoreCase));
-			IsMonoMac = assemblies.Any(a => a.GetName().Name.Equals("MonoMac", StringComparison.InvariantCultureIgnoreCase));
-			IsXamarinIOS = assemblies.Any(a => a.GetName().Name.Equals("Xamarin.iOS", StringComparison.InvariantCultureIgnoreCase));
-			IsXamarinAndroid = assemblies.Any(a => a.GetName().Name.Equals("Xamarin.Android", StringComparison.InvariantCultureIgnoreCase));
-
-			if (IsMonoMac)
-			{
-				Kind = PlatformKind.Posix;
-				Name = PlatformName.MacOSX;
-			}
-
-			if (Name == PlatformName.Posix && File.Exists("/System/Library/CoreServices/SystemVersion.plist")) 
-			{
-				Name = PlatformName.MacOSX;
-			}
-
-			if (IsXamarinIOS || IsMonoTouch)
-			{
-				// Kind = PlatformKind.__Internal;
-				// Name = PlatformName.__Internal;
-
-				Is__Internal = true;
-			}
-
-			SetupImplementation(typeof(Platform));
-		}
-
-		public static bool IsMono { get; private set; }
-
-		public static bool IsMonoMac { get; private set; }
-
-		public static bool IsMonoTouch { get; private set; }
-
-		public static bool IsXamarinIOS { get; private set; }
-
-		public static bool IsXamarinAndroid { get; private set; }
-
-		public static void ExpandPaths(IList<string> stream,
-			string extension, string path)
-		{
-			ExpandPaths(stream, extension, path != null ? new string[] { path } : null);
-		}
-
-		public static void ExpandPaths(IList<string> stream,
-			string extension, IEnumerable<string> paths) 
-		{
-			int pathsC = paths == null ? 0 : paths.Count();
-
-			foreach (string libraryPath in stream.ToArray())
-			{
-				if (-1 == libraryPath.IndexOf(extension)) continue;
-
-				int libraryPathI = stream.IndexOf(libraryPath);
-				stream.RemoveAt(libraryPathI);
-
-				if (pathsC == 0)
-				{
-					// just continue, don't Insert them again
-					continue;
-				}
-
-				if (pathsC == 1)
-				{
-					stream.Insert(libraryPathI, libraryPath.Replace(extension, paths.ElementAt(0)));
-					continue;
-				}
-
-				foreach (string realLibraryPath in paths)
-				{
-					stream.Insert(libraryPathI, libraryPath.Replace(extension, realLibraryPath));
-					++libraryPathI;
-				}
-
-			}
-		}
-
-		public static void SetupImplementation(Type platformDependant)
-		{
-			// Baseline by PlatformKind
-			string platformKind = Enum.GetName(typeof(PlatformKind), Platform.Kind);
-			AssignImplementations(platformDependant, platformKind);
-
-			// Overwrite by PlatformName
-			string platformName = Enum.GetName(typeof(PlatformName), Platform.Name);
-			if (platformName != platformKind)
-			{
-				AssignImplementations(platformDependant, platformName);
-			}
-
-            if (Is__Internal) 
-			{
-				AssignImplementations(platformDependant, "__Internal");
-			}
+            IsMono = Type.GetType("Mono.Runtime") != null;
+
+            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
+            IsMonoTouch = assemblies.Any(a => a.GetName().Name.Equals("MonoTouch", StringComparison.InvariantCultureIgnoreCase));
+            IsMonoMac = assemblies.Any(a => a.GetName().Name.Equals("MonoMac", StringComparison.InvariantCultureIgnoreCase));
+            IsXamarinIOS = assemblies.Any(a => a.GetName().Name.Equals("Xamarin.iOS", StringComparison.InvariantCultureIgnoreCase));
+            IsXamarinAndroid = assemblies.Any(a => a.GetName().Name.Equals("Xamarin.Android", StringComparison.InvariantCultureIgnoreCase));
+
+            if (IsMonoMac)
+            {
+                Kind = PlatformKind.Posix;
+                Name = PlatformName.MacOSX;
+            }
+
+            if (Name == PlatformName.Posix && File.Exists("/System/Library/CoreServices/SystemVersion.plist"))
+            {
+                Name = PlatformName.MacOSX;
+            }
+
+            if (IsXamarinIOS || IsMonoTouch)
+            {
+                // Kind = PlatformKind.__Internal;
+                // Name = PlatformName.__Internal;
+
+                Is__Internal = true;
+            }
+
+            SetupImplementation(typeof(Platform));
         }
 
-		private const BindingFlags bindings = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
-
-		private static void AssignImplementations(Type platformDependant, string implementationName)
-		{
-			Type platformImplementation = platformDependant.GetNestedType(implementationName, bindings);
-			// if (platformImplementation == null) return;
-
-			FieldInfo[] fields = platformDependant.GetFields(bindings);
-			foreach (FieldInfo field in fields)
-			{
-				Type fieldType = field.FieldType;
-				string delegateName = fieldType.Name;
-				MethodInfo methodInfo__internal = null;
-				FieldInfo fieldInfo__internal = null;
-
-				// TODO: This is mapping sodium.crypto_box to sodium.crypto_box__Internal. Should we also map them to sodium.__Internal.crypto_box?
-				if (implementationName == "__Internal")
-				{
-					if (delegateName.EndsWith("_delegate"))
-					{
-						// YOU now have
-						// public static readonly crypto_box_delegate box = crypto_box;
-
-						// YOU need
-						// public static readonly crypto_box_delegate box = crypto_box__Internal;
-
-						delegateName = delegateName.Substring(0, delegateName.Length - "_delegate".Length);
-						if (delegateName.Length > 0)
-						{
-							methodInfo__internal = platformDependant.GetMethod(delegateName + "__Internal", bindings);
-						}
-					}
-				}
-				if (methodInfo__internal == null && platformImplementation != null)
-				{
-					if (delegateName.EndsWith("Delegate"))
-					{
-						// YOU now have
-						// public static readonly UnmanagedLibrary LoadUnmanagedLibraryDelegate;
-
-						// YOU need
-						// public static readonly LoadUnmanagedLibraryDelegate LoadUnmanagedLibrary 
-						//     = Platform.__Internal.LoadUnmanagedLibrary;
-
-						delegateName = delegateName.Substring(0, delegateName.Length - "Delegate".Length);
-
-						methodInfo__internal = platformImplementation.GetMethod(delegateName, bindings);
-					}
-					else
-					{
-						methodInfo__internal = platformImplementation.GetMethod(field.Name, bindings);
-					}
-
-					if (methodInfo__internal == null)
-					{
-						fieldInfo__internal = platformImplementation.GetField(field.Name, bindings);
-					}
-				}
-
-				if (methodInfo__internal != null)
-				{
-					var delegat = Delegate.CreateDelegate(fieldType, methodInfo__internal);
-					field.SetValue(null, delegat);
-				}
-				else if (fieldInfo__internal != null)
-				{
-					object value = fieldInfo__internal.GetValue(null);
-					field.SetValue(null, value);
-				}
-				// else { field.SetValue(null, null); }
-			}
-		}
-
-		private static bool ExtractManifestResource(string resourceName, string outputPath)
-		{
-			if (File.Exists(outputPath))
-			{
-				// This is necessary to prevent access conflicts if multiple processes are run from the
-				// same location. The naming scheme implemented in UnmanagedLibrary should ensure that
-				// the correct version is always used.
-				return true;
-			}
-
-			Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
-
-			if (resourceStream == null)
-			{
-				// No manifest resources were compiled into the current assembly. This is likely a 'manual
-				// deployment' situation, so do not throw an exception at this point and allow all deployment
-				// paths to be searched.
-				return false;
-			}
-
-			try
-			{
-				using (FileStream fileStream = File.Create(outputPath))
-				{
-					resourceStream.CopyTo(fileStream);
-				}
-			}
-			catch (UnauthorizedAccessException)
-			{
-				// Caller does not have write permission for the current file
-				return false;
-			}
-
-			return true;
-		}
-
-	}
+        public static bool IsMono { get; private set; }
+
+        public static bool IsMonoMac { get; private set; }
+
+        public static bool IsMonoTouch { get; private set; }
+
+        public static bool IsXamarinIOS { get; private set; }
+
+        public static bool IsXamarinAndroid { get; private set; }
+
+        public static void ExpandPaths(IList<string> stream,
+            string extension, string path)
+        {
+            ExpandPaths(stream, extension, path != null ? new string[] { path } : null);
+        }
+
+        public static void ExpandPaths(IList<string> stream,
+            string extension, IEnumerable<string> paths)
+        {
+            int pathsC = paths == null ? 0 : paths.Count();
+
+            foreach (string libraryPath in stream.ToArray())
+            {
+                if (-1 == libraryPath.IndexOf(extension)) continue;
+
+                int libraryPathI = stream.IndexOf(libraryPath);
+                stream.RemoveAt(libraryPathI);
+
+                if (pathsC == 0)
+                {
+                    // just continue, don't Insert them again
+                    continue;
+                }
+
+                if (pathsC == 1)
+                {
+                    stream.Insert(libraryPathI, libraryPath.Replace(extension, paths.ElementAt(0)));
+                    continue;
+                }
+
+                foreach (string realLibraryPath in paths)
+                {
+                    stream.Insert(libraryPathI, libraryPath.Replace(extension, realLibraryPath));
+                    ++libraryPathI;
+                }
+
+            }
+        }
+
+        public static void SetupImplementation(Type platformDependant)
+        {
+            // Baseline by PlatformKind
+            string platformKind = Enum.GetName(typeof(PlatformKind), Platform.Kind);
+            AssignImplementations(platformDependant, platformKind);
+
+            // Overwrite by PlatformName
+            string platformName = Enum.GetName(typeof(PlatformName), Platform.Name);
+            if (platformName != platformKind)
+            {
+                AssignImplementations(platformDependant, platformName);
+            }
+
+            if (Is__Internal)
+            {
+                AssignImplementations(platformDependant, "__Internal");
+            }
+        }
+
+        private const BindingFlags bindings = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
+
+        private static void AssignImplementations(Type platformDependant, string implementationName)
+        {
+            Type platformImplementation = platformDependant.GetNestedType(implementationName, bindings);
+            // if (platformImplementation == null) return;
+
+            FieldInfo[] fields = platformDependant.GetFields(bindings);
+            foreach (FieldInfo field in fields)
+            {
+                Type fieldType = field.FieldType;
+                string delegateName = fieldType.Name;
+                MethodInfo methodInfo__internal = null;
+                FieldInfo fieldInfo__internal = null;
+
+                // TODO: This is mapping sodium.crypto_box to sodium.crypto_box__Internal. Should we also map them to sodium.__Internal.crypto_box?
+                if (implementationName == "__Internal")
+                {
+                    if (delegateName.EndsWith("_delegate"))
+                    {
+                        // YOU now have
+                        // public static readonly crypto_box_delegate box = crypto_box;
+
+                        // YOU need
+                        // public static readonly crypto_box_delegate box = crypto_box__Internal;
+
+                        delegateName = delegateName.Substring(0, delegateName.Length - "_delegate".Length);
+                        if (delegateName.Length > 0)
+                        {
+                            methodInfo__internal = platformDependant.GetMethod(delegateName + "__Internal", bindings);
+                        }
+                    }
+                }
+                if (methodInfo__internal == null && platformImplementation != null)
+                {
+                    if (delegateName.EndsWith("Delegate"))
+                    {
+                        // YOU now have
+                        // public static readonly UnmanagedLibrary LoadUnmanagedLibraryDelegate;
+
+                        // YOU need
+                        // public static readonly LoadUnmanagedLibraryDelegate LoadUnmanagedLibrary 
+                        //     = Platform.__Internal.LoadUnmanagedLibrary;
+
+                        delegateName = delegateName.Substring(0, delegateName.Length - "Delegate".Length);
+
+                        methodInfo__internal = platformImplementation.GetMethod(delegateName, bindings);
+                    }
+                    else
+                    {
+                        methodInfo__internal = platformImplementation.GetMethod(field.Name, bindings);
+                    }
+
+                    if (methodInfo__internal == null)
+                    {
+                        fieldInfo__internal = platformImplementation.GetField(field.Name, bindings);
+                    }
+                }
+
+                if (methodInfo__internal != null)
+                {
+                    var delegat = Delegate.CreateDelegate(fieldType, methodInfo__internal);
+                    field.SetValue(null, delegat);
+                }
+                else if (fieldInfo__internal != null)
+                {
+                    object value = fieldInfo__internal.GetValue(null);
+                    field.SetValue(null, value);
+                }
+                // else { field.SetValue(null, null); }
+            }
+        }
+
+        private static bool ExtractManifestResource(string resourceName, string outputPath)
+        {
+            if (File.Exists(outputPath))
+            {
+                // This is necessary to prevent access conflicts if multiple processes are run from the
+                // same location. The naming scheme implemented in UnmanagedLibrary should ensure that
+                // the correct version is always used.
+                return true;
+            }
+
+            Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
+
+            if (resourceStream == null)
+            {
+                // No manifest resources were compiled into the current assembly. This is likely a 'manual
+                // deployment' situation, so do not throw an exception at this point and allow all deployment
+                // paths to be searched.
+                return false;
+            }
+
+            try
+            {
+                using (FileStream fileStream = File.Create(outputPath))
+                {
+                    resourceStream.CopyTo(fileStream);
+                }
+            }
+            catch (UnauthorizedAccessException)
+            {
+                // Caller does not have write permission for the current file
+                return false;
+            }
+
+            return true;
+        }
+
+    }
 }

+ 105 - 107
dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/Zmq/ZContext.cs

@@ -1,64 +1,62 @@
 using System;
-using System.Text;
-using System.Threading;
 
- 
+
 
 namespace Sers.CL.Zmq.FullDuplex.Zmq
 {
-	/// <summary>
-	/// Creates <see cref="ZSocket"/> instances within a process boundary.
-	/// </summary>
-	public sealed class ZContext : IDisposable
-	{	 
-
-		public static readonly ZContext Current = new ZContext();
-		 
-
-		/// <summary>
-		/// Create a <see cref="ZContext"/> instance.
-		/// </summary>
-		/// <returns><see cref="ZContext"/></returns>
-		public ZContext()
-		{
-			_contextPtr = zmq.ctx_new();
-
-			if (_contextPtr == IntPtr.Zero)
-			{
-				throw new InvalidProgramException("zmq_ctx_new");
-			}
-		}
-
- 
-
-		~ZContext()
-		{
-			Dispose(false);
-		}
-
-		private IntPtr _contextPtr;
-
-		/// <summary>
-		/// Gets a handle to the native ZeroMQ context.
-		/// </summary>
-		public IntPtr ContextPtr
-		{
-			get { return _contextPtr; }
-		}
-
-		           
- 
-
-		/// <summary>
-		/// Shutdown the ZeroMQ context.
-		/// </summary>
-		public bool Shutdown()
-		{
+    /// <summary>
+    /// Creates <see cref="ZSocket"/> instances within a process boundary.
+    /// </summary>
+    public sealed class ZContext : IDisposable
+    {
+
+        public static readonly ZContext Current = new ZContext();
+
+
+        /// <summary>
+        /// Create a <see cref="ZContext"/> instance.
+        /// </summary>
+        /// <returns><see cref="ZContext"/></returns>
+        public ZContext()
+        {
+            _contextPtr = zmq.ctx_new();
+
             if (_contextPtr == IntPtr.Zero)
-				return true;
+            {
+                throw new InvalidProgramException("zmq_ctx_new");
+            }
+        }
+
+
+
+        ~ZContext()
+        {
+            Dispose(false);
+        }
+
+        private IntPtr _contextPtr;
+
+        /// <summary>
+        /// Gets a handle to the native ZeroMQ context.
+        /// </summary>
+        public IntPtr ContextPtr
+        {
+            get { return _contextPtr; }
+        }
+
+
+
 
-			while (-1 == zmq.ctx_shutdown(_contextPtr))
-			{
+        /// <summary>
+        /// Shutdown the ZeroMQ context.
+        /// </summary>
+        public bool Shutdown()
+        {
+            if (_contextPtr == IntPtr.Zero)
+                return true;
+
+            while (-1 == zmq.ctx_shutdown(_contextPtr))
+            {
                 int errno = zmq.errno();
                 if (errno == (int)ZError.EINTR)
                 {
@@ -67,34 +65,34 @@ namespace Sers.CL.Zmq.FullDuplex.Zmq
                 return false;
             }
 
-			// don't _contextPtr = IntPtr.Zero;
-			return true;
-		}
-
-		/// <summary>
-		/// Terminate the ZeroMQ context.
-		/// </summary>
-		public void Terminate()
-		{
-			 
-			if (!Terminate(out int error))
-			{
-				throw new Exception("zmq error: errno " + error);
-			}
-		}
-
-		/// <summary>
-		/// Terminate the ZeroMQ context.
-		/// </summary>
-		public bool Terminate(out int error)
-		{
+            // don't _contextPtr = IntPtr.Zero;
+            return true;
+        }
+
+        /// <summary>
+        /// Terminate the ZeroMQ context.
+        /// </summary>
+        public void Terminate()
+        {
+
+            if (!Terminate(out int error))
+            {
+                throw new Exception("zmq error: errno " + error);
+            }
+        }
+
+        /// <summary>
+        /// Terminate the ZeroMQ context.
+        /// </summary>
+        public bool Terminate(out int error)
+        {
             error = 0;
 
             if (_contextPtr == IntPtr.Zero)
-				return true;
+                return true;
 
-			while (-1 == zmq.ctx_term(_contextPtr))
-			{
+            while (-1 == zmq.ctx_term(_contextPtr))
+            {
                 int errno = zmq.errno();
                 if (errno == (int)ZError.EINTR)
                 {
@@ -102,33 +100,33 @@ namespace Sers.CL.Zmq.FullDuplex.Zmq
                 }
                 // Maybe ZError.EFAULT
 
-				return false;
-			}
-
-			_contextPtr = IntPtr.Zero;
-			return true;
-		}
-
-		public void Dispose()
-		{
-			GC.SuppressFinalize(this);
-			Dispose(true);
-		}
-
-		void Dispose(bool disposing)
-		{
-			if (disposing)
-			{				 
-				Terminate(out var _);
-			}
-		}
-
-		private void EnsureNotDisposed()
-		{
-			if (_contextPtr == IntPtr.Zero)
-			{
-				throw new ObjectDisposedException(GetType().FullName);
-			}
-		}
-	}
+                return false;
+            }
+
+            _contextPtr = IntPtr.Zero;
+            return true;
+        }
+
+        public void Dispose()
+        {
+            GC.SuppressFinalize(this);
+            Dispose(true);
+        }
+
+        void Dispose(bool disposing)
+        {
+            if (disposing)
+            {
+                Terminate(out var _);
+            }
+        }
+
+        private void EnsureNotDisposed()
+        {
+            if (_contextPtr == IntPtr.Zero)
+            {
+                throw new ObjectDisposedException(GetType().FullName);
+            }
+        }
+    }
 }

+ 62 - 66
dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/Zmq/ZError.cs

@@ -1,71 +1,67 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-
-namespace Sers.CL.Zmq.FullDuplex.Zmq
+namespace Sers.CL.Zmq.FullDuplex.Zmq
 {
-    public enum ZError:int
+    public enum ZError : int
     {
-                EPERM = 1,
-                ENOENT = 2,
-                ESRCH = 3,
-                EINTR = 4,
-                EIO = 5,
-                ENXIO = 6,
-                E2BIG = 7,
-                ENOEXEC = 8,
-                EBADF = 9,
-                ECHILD = 10,
-                EAGAIN = 11,
-                ENOMEM = 12,
-                EACCES = 13,
-                EFAULT = 14,
-                ENOTBLK = 15,
-                EBUSY = 16,
-                EEXIST = 17,
-                EXDEV = 18,
-                ENODEV = 19,
-                ENOTDIR = 20,
-                EISDIR = 21,
-                EINVAL = 22,
-                ENFILE = 23,
-                EMFILE = 24,
-                ENOTTY = 25,
-                ETXTBSY = 26,
-                EFBIG = 27,
-                ENOSPC = 28,
-                ESPIPE = 29,
-                EROFS = 30,
-                EMLINK = 31,
-                EPIPE = 32,
-                EDOM = 33,
-                ERANGE = 34, // 34
+        EPERM = 1,
+        ENOENT = 2,
+        ESRCH = 3,
+        EINTR = 4,
+        EIO = 5,
+        ENXIO = 6,
+        E2BIG = 7,
+        ENOEXEC = 8,
+        EBADF = 9,
+        ECHILD = 10,
+        EAGAIN = 11,
+        ENOMEM = 12,
+        EACCES = 13,
+        EFAULT = 14,
+        ENOTBLK = 15,
+        EBUSY = 16,
+        EEXIST = 17,
+        EXDEV = 18,
+        ENODEV = 19,
+        ENOTDIR = 20,
+        EISDIR = 21,
+        EINVAL = 22,
+        ENFILE = 23,
+        EMFILE = 24,
+        ENOTTY = 25,
+        ETXTBSY = 26,
+        EFBIG = 27,
+        ENOSPC = 28,
+        ESPIPE = 29,
+        EROFS = 30,
+        EMLINK = 31,
+        EPIPE = 32,
+        EDOM = 33,
+        ERANGE = 34, // 34
 
-                ENOTSUP = 129,
-                EPROTONOSUPPORT = 135,
-                ENOBUFS = 119,
-                ENETDOWN = 116,
-                EADDRINUSE = 100,
-                EADDRNOTAVAIL = 101,
-                ECONNREFUSED = 107,
-                EINPROGRESS = 112,
-                ENOTSOCK = 128,
-                EMSGSIZE = 115,
-                // as of here are differences to nanomsg
-                EAFNOSUPPORT = 102,
-                ENETUNREACH = 118,
-                ECONNABORTED = 106,
-                ECONNRESET = 108,
-                ENOTCONN = 126,
-                ETIMEDOUT = 138,
-                EHOSTUNREACH = 110,
-                ENETRESET = 117,
+        ENOTSUP = 129,
+        EPROTONOSUPPORT = 135,
+        ENOBUFS = 119,
+        ENETDOWN = 116,
+        EADDRINUSE = 100,
+        EADDRNOTAVAIL = 101,
+        ECONNREFUSED = 107,
+        EINPROGRESS = 112,
+        ENOTSOCK = 128,
+        EMSGSIZE = 115,
+        // as of here are differences to nanomsg
+        EAFNOSUPPORT = 102,
+        ENETUNREACH = 118,
+        ECONNABORTED = 106,
+        ECONNRESET = 108,
+        ENOTCONN = 126,
+        ETIMEDOUT = 138,
+        EHOSTUNREACH = 110,
+        ENETRESET = 117,
 
-                /*  Native ZeroMQ error codes. */
-                //EFSM = HAUSNUMERO + 51,
-                //ENOCOMPATPROTO = HAUSNUMERO + 52,
-                //ETERM = HAUSNUMERO + 53,
-                //EMTHREAD = HAUSNUMERO + 54
-           
-}
+        /*  Native ZeroMQ error codes. */
+        //EFSM = HAUSNUMERO + 51,
+        //ENOCOMPATPROTO = HAUSNUMERO + 52,
+        //ETERM = HAUSNUMERO + 53,
+        //EMTHREAD = HAUSNUMERO + 54
+
+    }
 }

+ 132 - 134
dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/Zmq/ZSocket.cs

@@ -1,73 +1,71 @@
 using System;
 using System.Collections.Generic;
-using System.Linq;
 using System.Runtime.InteropServices;
-using System.Threading;
 
- 
-namespace  Sers.CL.Zmq.FullDuplex.Zmq
+
+namespace Sers.CL.Zmq.FullDuplex.Zmq
 {
-	/// <summary>
-	/// Sends and receives messages, single frames and byte frames across ZeroMQ.
-	/// </summary>
-	public class ZSocket : IDisposable
-	{
-		  
-		private ZContext _context;
-
-		private IntPtr _socketPtr;
-
-		private ZSocketType _socketType;
-		
-		/// <summary>
-		/// Create a <see cref="ZSocket"/> instance.
-		/// You are using ZContext.Current!
-		/// </summary>
-		/// <returns><see cref="ZSocket"/></returns>
-		public ZSocket(ZSocketType socketType) : this (ZContext.Current, socketType) { }
-
-		/// <summary>
-		/// Create a <see cref="ZSocket"/> instance.
-		/// </summary>
-		/// <returns><see cref="ZSocket"/></returns>
-		public ZSocket(ZContext context, ZSocketType socketType)
-		{
-			_context = context;
-			_socketType = socketType;
-
-		 
-			if (!Initialize(out var error))
-			{
+    /// <summary>
+    /// Sends and receives messages, single frames and byte frames across ZeroMQ.
+    /// </summary>
+    public class ZSocket : IDisposable
+    {
+
+        private ZContext _context;
+
+        private IntPtr _socketPtr;
+
+        private ZSocketType _socketType;
+
+        /// <summary>
+        /// Create a <see cref="ZSocket"/> instance.
+        /// You are using ZContext.Current!
+        /// </summary>
+        /// <returns><see cref="ZSocket"/></returns>
+        public ZSocket(ZSocketType socketType) : this(ZContext.Current, socketType) { }
+
+        /// <summary>
+        /// Create a <see cref="ZSocket"/> instance.
+        /// </summary>
+        /// <returns><see cref="ZSocket"/></returns>
+        public ZSocket(ZContext context, ZSocketType socketType)
+        {
+            _context = context;
+            _socketType = socketType;
+
+
+            if (!Initialize(out var error))
+            {
                 throw new Exception("zmq error: errno " + error);
             }
-		}
+        }
 
-		protected ZSocket() { }
+        protected ZSocket() { }
 
-		protected bool Initialize(out int error)
-		{
-			error = 0;
+        protected bool Initialize(out int error)
+        {
+            error = 0;
 
-			if (IntPtr.Zero == (_socketPtr = zmq.socket(_context.ContextPtr, (Int32)_socketType)))
-			{
+            if (IntPtr.Zero == (_socketPtr = zmq.socket(_context.ContextPtr, (Int32)_socketType)))
+            {
                 error = zmq.errno();
                 return false;
-			}
-			return true;
-		}
-
-		/// <summary>
-		/// Finalizes an instance of the <see cref="ZSocket"/> class.
-		/// </summary>
-		~ZSocket()
-		{
-			Dispose(false);
-		}
-
-		public void Dispose()
-		{
-			Dispose(true);
-			GC.SuppressFinalize(this);
+            }
+            return true;
+        }
+
+        /// <summary>
+        /// Finalizes an instance of the <see cref="ZSocket"/> class.
+        /// </summary>
+        ~ZSocket()
+        {
+            Dispose(false);
+        }
+
+        public void Dispose()
+        {
+            Dispose(true);
+            GC.SuppressFinalize(this);
         }
 
         /// <summary>
@@ -75,85 +73,85 @@ namespace  Sers.CL.Zmq.FullDuplex.Zmq
         /// </summary>
         /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
         protected virtual void Dispose(bool disposing)
-		{
-			if (disposing)
-			{			 
-				Close(out var error);
-			}
-		}
-
-		/// <summary>
-		/// Close the current socket.
-		/// </summary>
-		public void Close()
-		{
-		 
-			if (!Close(out var error))
-			{
+        {
+            if (disposing)
+            {
+                Close(out var error);
+            }
+        }
+
+        /// <summary>
+        /// Close the current socket.
+        /// </summary>
+        public void Close()
+        {
+
+            if (!Close(out var error))
+            {
                 throw new Exception("zmq error: errno " + error);
             }
-		}
-
-		/// <summary>
-		/// Close the current socket.
-		/// </summary>
-		public bool Close(out int error)
-		{
-			error = 0;
-			if (_socketPtr == IntPtr.Zero) return true;
-
-			if (-1 == zmq.close(_socketPtr))
-			{
+        }
+
+        /// <summary>
+        /// Close the current socket.
+        /// </summary>
+        public bool Close(out int error)
+        {
+            error = 0;
+            if (_socketPtr == IntPtr.Zero) return true;
+
+            if (-1 == zmq.close(_socketPtr))
+            {
                 error = zmq.errno();
                 return false;
-			}
-			_socketPtr = IntPtr.Zero;
-			return true;
-		}
+            }
+            _socketPtr = IntPtr.Zero;
+            return true;
+        }
+
+
+
 
-	 
 
-	 
 
-	 
 
-		/// <summary>
-		/// Bind the specified endpoint.
-		/// </summary>
-		/// <param name="endpoint">A string consisting of a transport and an address, formatted as <c><em>transport</em>://<em>address</em></c>.</param>
-		public void Bind(string endpoint)
-		{
+        /// <summary>
+        /// Bind the specified endpoint.
+        /// </summary>
+        /// <param name="endpoint">A string consisting of a transport and an address, formatted as <c><em>transport</em>://<em>address</em></c>.</param>
+        public void Bind(string endpoint)
+        {
             if (-1 == zmq.bind(_socketPtr, endpoint))
             {
                 int errno = zmq.errno();
                 zmq.ThrowErrno(errno);
-            }         
+            }
         }
-         
-
-		/// <summary>
-		/// Connect the specified endpoint.
-		/// </summary>
-		/// <param name="endpoint">A string consisting of a transport and an address, formatted as <c><em>transport</em>://<em>address</em></c>.</param>
-		public void Connect(string endpoint)
-		{
+
+
+        /// <summary>
+        /// Connect the specified endpoint.
+        /// </summary>
+        /// <param name="endpoint">A string consisting of a transport and an address, formatted as <c><em>transport</em>://<em>address</em></c>.</param>
+        public void Connect(string endpoint)
+        {
             if (-1 == zmq.connect(_socketPtr, endpoint))
             {
-                int errno = zmq.errno();               
+                int errno = zmq.errno();
                 zmq.ThrowErrno(errno);
-            } 
+            }
         }
 
-		/// <summary>
-		/// Disconnect the specified endpoint.
-		/// </summary>
-		public void Disconnect(string endpoint)
-		{			 
-			if (!Disconnect(endpoint, out var errno))
-			{
-                zmq.ThrowErrno(errno);    
+        /// <summary>
+        /// Disconnect the specified endpoint.
+        /// </summary>
+        public void Disconnect(string endpoint)
+        {
+            if (!Disconnect(endpoint, out var errno))
+            {
+                zmq.ThrowErrno(errno);
             }
-		}
+        }
 
         /// <summary>
         /// Disconnect the specified endpoint.
@@ -161,8 +159,8 @@ namespace  Sers.CL.Zmq.FullDuplex.Zmq
         /// <param name="endpoint">A string consisting of a transport and an address, formatted as <c><em>transport</em>://<em>address</em></c>.</param>
         /// <param name="errno"></param>
 		public bool Disconnect(string endpoint, out int errno)
-		{
-            errno =  0;
+        {
+            errno = 0;
 
             if (-1 == zmq.disconnect(_socketPtr, endpoint))
             {
@@ -170,7 +168,7 @@ namespace  Sers.CL.Zmq.FullDuplex.Zmq
                 return false;
             }
             return true;
-		}
+        }
 
 
         #region OptionBytes
@@ -213,7 +211,7 @@ namespace  Sers.CL.Zmq.FullDuplex.Zmq
                         continue;
                     }
                     zmq.ThrowErrno(errno);
-                }          
+                }
             }
         }
         #endregion
@@ -221,28 +219,28 @@ namespace  Sers.CL.Zmq.FullDuplex.Zmq
         #region option int32
         public bool ReceiveMore
         {
-            get { return GetOptionInt32(ZSocketOption.RCVMORE,out int value) && value == 1; }
+            get { return GetOptionInt32(ZSocketOption.RCVMORE, out int value) && value == 1; }
         }
 
         static readonly int Int32OptionLength = Marshal.SizeOf(typeof(Int32));
 
-       
+
 
         public bool GetOptionInt32(ZSocketOption option, out Int32 value)
-        {          
-            value = default(Int32);         
+        {
+            value = default(Int32);
             int optionLength = Int32OptionLength;
             using (var optionValue = new DispoIntPtr(optionLength))
             {
                 GetOption(option, optionValue.Ptr, ref optionLength);
-                
-                value = Marshal.ReadInt32(optionValue.Ptr);  
+
+                value = Marshal.ReadInt32(optionValue.Ptr);
             }
             return true;
         }
         private void GetOption(ZSocketOption option, IntPtr optionValue, ref int optionLength)
         {
-          
+
             using (var optionLengthP = new DispoIntPtr(IntPtr.Size))
             {
                 if (IntPtr.Size == 4)
@@ -258,7 +256,7 @@ namespace  Sers.CL.Zmq.FullDuplex.Zmq
                     if (errno == (int)ZError.EINTR)
                     {
                         continue;
-                    }                 
+                    }
                     zmq.ThrowErrno(errno);
                 }
 
@@ -269,12 +267,12 @@ namespace  Sers.CL.Zmq.FullDuplex.Zmq
                 else
                     throw new PlatformNotSupportedException();
             }
- 
+
         }
         #endregion
 
-        public List<byte[]>  ReceiveMessage()
-        {          
+        public List<byte[]> ReceiveMessage()
+        {
             var message = new List<byte[]>();
 
             do
@@ -291,7 +289,7 @@ namespace  Sers.CL.Zmq.FullDuplex.Zmq
         public void SendMessage(byte[][] message)
         {
             var t = 0;
-            for (; t < message.Length-1; t++)
+            for (; t < message.Length - 1; t++)
             {
                 zmq.SendMessage(_socketPtr, message[t], (int)ZSocketFlags.More);
             }

+ 16 - 20
dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/Zmq/ZSocketFlags.cs

@@ -1,27 +1,23 @@
 using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Reflection;
-using System.Runtime.InteropServices;
 
 namespace Sers.CL.Zmq.FullDuplex.Zmq
 {
-	[Flags]
-	public enum ZSocketFlags : int
-	{
-		/// <summary>
-		/// No socket flags are specified.
-		/// </summary>
-		None = 0,
+    [Flags]
+    public enum ZSocketFlags : int
+    {
+        /// <summary>
+        /// No socket flags are specified.
+        /// </summary>
+        None = 0,
 
-		/// <summary>
-		/// The operation should be performed in non-blocking mode.
-		/// </summary>
-		DontWait = 1,
+        /// <summary>
+        /// The operation should be performed in non-blocking mode.
+        /// </summary>
+        DontWait = 1,
 
-		/// <summary>
-		/// The message being sent is a multi-part message, and that further message parts are to follow.
-		/// </summary>
-		More = 2
-	}
+        /// <summary>
+        /// The message being sent is a multi-part message, and that further message parts are to follow.
+        /// </summary>
+        More = 2
+    }
 }

+ 82 - 82
dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/Zmq/ZSocketOption.cs

@@ -1,87 +1,87 @@
- 
+
 
 namespace Sers.CL.Zmq.FullDuplex.Zmq
 {
-	public enum ZSocketOption : int
-	{
-		AFFINITY = 4,
-		IDENTITY = 5,
-		SUBSCRIBE = 6,
-		UNSUBSCRIBE = 7,
-		RATE = 8,
-		RECOVERY_IVL = 9,
-		SNDBUF = 11,
-		RCVBUF = 12,
-		RCVMORE = 13,
-		FD = 14,
-		EVENTS = 15,
-		TYPE = 16,
-		LINGER = 17,
-		RECONNECT_IVL = 18,
-		BACKLOG = 19,
-		RECONNECT_IVL_MAX = 21,
-		MAX_MSG_SIZE = 22,
-		SNDHWM = 23,
-		RCVHWM = 24,
-		MULTICAST_HOPS = 25,
-		RCVTIMEO = 27,
-		SNDTIMEO = 28,
-		LAST_ENDPOINT = 32,
-		ROUTER_MANDATORY = 33,
-		TCP_KEEPALIVE = 34,
-		TCP_KEEPALIVE_CNT = 35,
-		TCP_KEEPALIVE_IDLE = 36,
-		TCP_KEEPALIVE_INTVL = 37,
-		IMMEDIATE = 39,
-		XPUB_VERBOSE = 40,
-		ROUTER_RAW = 41,
-		IPV6 = 42,
-		MECHANISM = 43,
-		PLAIN_SERVER = 44,
-		PLAIN_USERNAME = 45,
-		PLAIN_PASSWORD = 46,
-		CURVE_SERVER = 47,
-		CURVE_PUBLICKEY = 48,
-		CURVE_SECRETKEY = 49,
-		CURVE_SERVERKEY = 50,
-		PROBE_ROUTER = 51,
-		REQ_CORRELATE = 52,
-		REQ_RELAXED = 53,
-		CONFLATE = 54,
-		ZAP_DOMAIN = 55,
-		ROUTER_HANDOVER = 56,
-		TOS = 57,
-		CONNECT_RID = 61,
-		GSSAPI_SERVER = 62,
-		GSSAPI_PRINCIPAL = 63,
-		GSSAPI_SERVICE_PRINCIPAL = 64,
-		GSSAPI_PLAINTEXT = 65,
-		HANDSHAKE_IVL = 66,
-		IDENTITY_FD = 67,
-		SOCKS_PROXY = 68,
-		XPUB_NODROP = 69,
-		BLOCKY = 70,
-		XPUB_MANUAL = 71,
-		XPUB_WELCOME_MSG = 72,
-		STREAM_NOTIFY = 73,
-		INVERT_MATCHING = 74,
-		HEARTBEAT_IVL = 75,
-		HEARTBEAT_TTL = 76,
-		HEARTBEAT_TIMEOUT = 77,
-		XPUB_VERBOSE_UNSUBSCRIBE = 78,
-		CONNECT_TIMEOUT = 79,
-		TCP_RETRANSMIT_TIMEOUT = 80,
-		THREAD_SAFE = 81,
+    public enum ZSocketOption : int
+    {
+        AFFINITY = 4,
+        IDENTITY = 5,
+        SUBSCRIBE = 6,
+        UNSUBSCRIBE = 7,
+        RATE = 8,
+        RECOVERY_IVL = 9,
+        SNDBUF = 11,
+        RCVBUF = 12,
+        RCVMORE = 13,
+        FD = 14,
+        EVENTS = 15,
+        TYPE = 16,
+        LINGER = 17,
+        RECONNECT_IVL = 18,
+        BACKLOG = 19,
+        RECONNECT_IVL_MAX = 21,
+        MAX_MSG_SIZE = 22,
+        SNDHWM = 23,
+        RCVHWM = 24,
+        MULTICAST_HOPS = 25,
+        RCVTIMEO = 27,
+        SNDTIMEO = 28,
+        LAST_ENDPOINT = 32,
+        ROUTER_MANDATORY = 33,
+        TCP_KEEPALIVE = 34,
+        TCP_KEEPALIVE_CNT = 35,
+        TCP_KEEPALIVE_IDLE = 36,
+        TCP_KEEPALIVE_INTVL = 37,
+        IMMEDIATE = 39,
+        XPUB_VERBOSE = 40,
+        ROUTER_RAW = 41,
+        IPV6 = 42,
+        MECHANISM = 43,
+        PLAIN_SERVER = 44,
+        PLAIN_USERNAME = 45,
+        PLAIN_PASSWORD = 46,
+        CURVE_SERVER = 47,
+        CURVE_PUBLICKEY = 48,
+        CURVE_SECRETKEY = 49,
+        CURVE_SERVERKEY = 50,
+        PROBE_ROUTER = 51,
+        REQ_CORRELATE = 52,
+        REQ_RELAXED = 53,
+        CONFLATE = 54,
+        ZAP_DOMAIN = 55,
+        ROUTER_HANDOVER = 56,
+        TOS = 57,
+        CONNECT_RID = 61,
+        GSSAPI_SERVER = 62,
+        GSSAPI_PRINCIPAL = 63,
+        GSSAPI_SERVICE_PRINCIPAL = 64,
+        GSSAPI_PLAINTEXT = 65,
+        HANDSHAKE_IVL = 66,
+        IDENTITY_FD = 67,
+        SOCKS_PROXY = 68,
+        XPUB_NODROP = 69,
+        BLOCKY = 70,
+        XPUB_MANUAL = 71,
+        XPUB_WELCOME_MSG = 72,
+        STREAM_NOTIFY = 73,
+        INVERT_MATCHING = 74,
+        HEARTBEAT_IVL = 75,
+        HEARTBEAT_TTL = 76,
+        HEARTBEAT_TIMEOUT = 77,
+        XPUB_VERBOSE_UNSUBSCRIBE = 78,
+        CONNECT_TIMEOUT = 79,
+        TCP_RETRANSMIT_TIMEOUT = 80,
+        THREAD_SAFE = 81,
 
-		/* Deprecated options and aliases */
-		TCP_ACCEPT_FILTER = 38,
-		IPC_FILTER_PID = 58,
-		IPC_FILTER_UID = 59,
-		IPC_FILTER_GID = 60,
-		IPV4_ONLY = 31,
-		DELAY_ATTACH_ON_CONNECT = 39, // IMMEDIATE,
-		NOBLOCK                 = 1,  // DONTWAIT,
-		FAIL_UNROUTABLE         = 33, // ROUTER_MANDATORY,
-		ROUTER_BEHAVIOR         = 33, // ROUTER_MANDATORY,
-	}
+        /* Deprecated options and aliases */
+        TCP_ACCEPT_FILTER = 38,
+        IPC_FILTER_PID = 58,
+        IPC_FILTER_UID = 59,
+        IPC_FILTER_GID = 60,
+        IPV4_ONLY = 31,
+        DELAY_ATTACH_ON_CONNECT = 39, // IMMEDIATE,
+        NOBLOCK = 1,  // DONTWAIT,
+        FAIL_UNROUTABLE = 33, // ROUTER_MANDATORY,
+        ROUTER_BEHAVIOR = 33, // ROUTER_MANDATORY,
+    }
 }

+ 68 - 68
dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/Zmq/ZSocketType.cs

@@ -1,84 +1,84 @@
- 
+
 
 namespace Sers.CL.Zmq.FullDuplex.Zmq
 {
-	public enum ZSocketType : int
-	{
-		None = -1,
+    public enum ZSocketType : int
+    {
+        None = -1,
 
-		/// <summary>
-		/// Exclusive Pair
-		/// </summary>
-		PAIR,
+        /// <summary>
+        /// Exclusive Pair
+        /// </summary>
+        PAIR,
 
-		/// <summary>
-		/// Publish
-		/// </summary>
-		PUB,
+        /// <summary>
+        /// Publish
+        /// </summary>
+        PUB,
 
-		/// <summary>
-		/// Subscribe
-		/// </summary>
-		SUB,
+        /// <summary>
+        /// Subscribe
+        /// </summary>
+        SUB,
 
-		/// <summary>
-		/// Request
-		/// </summary>
-		REQ,
+        /// <summary>
+        /// Request
+        /// </summary>
+        REQ,
 
-		/// <summary>
-		/// Reply / Response
-		/// </summary>
-		REP,
+        /// <summary>
+        /// Reply / Response
+        /// </summary>
+        REP,
 
-		/// <summary>
-		/// Dealer
-		/// </summary>
-		DEALER,
+        /// <summary>
+        /// Dealer
+        /// </summary>
+        DEALER,
 
-		/// <summary>
-		/// Router
-		/// </summary>
-		/// <remarks>
-		/// When receiving messages a <see cref="ROUTER"/> socket shall prepend a message
-		/// part containing the identity of the originating peer to the message before
-		/// passing it to the application. When sending messages a ZMQ_ROUTER socket shall remove
-		/// the first part of the message and use it to determine the identity of the peer the message
-		/// shall be routed to. If the peer does not exist anymore the message shall be silently discarded.
-		/// </remarks>
-		ROUTER,
+        /// <summary>
+        /// Router
+        /// </summary>
+        /// <remarks>
+        /// When receiving messages a <see cref="ROUTER"/> socket shall prepend a message
+        /// part containing the identity of the originating peer to the message before
+        /// passing it to the application. When sending messages a ZMQ_ROUTER socket shall remove
+        /// the first part of the message and use it to determine the identity of the peer the message
+        /// shall be routed to. If the peer does not exist anymore the message shall be silently discarded.
+        /// </remarks>
+        ROUTER,
 
-		/// <summary>
-		/// Pull
-		/// </summary>
-		PULL,
+        /// <summary>
+        /// Pull
+        /// </summary>
+        PULL,
 
-		/// <summary>
-		/// Push
-		/// </summary>
-		PUSH,
+        /// <summary>
+        /// Push
+        /// </summary>
+        PUSH,
 
-		/// <summary>
-		/// XPublisher
-		/// </summary>
-		/// <remarks>
-		/// Subscription message is a byte '1' (for subscriptions) or byte '0' (for unsubscriptions) followed by the subscription body.
-		/// </remarks>
-		XPUB,
+        /// <summary>
+        /// XPublisher
+        /// </summary>
+        /// <remarks>
+        /// Subscription message is a byte '1' (for subscriptions) or byte '0' (for unsubscriptions) followed by the subscription body.
+        /// </remarks>
+        XPUB,
 
-		/// <summary>
-		/// XSubscriber
-		/// </summary>
-		/// <remarks>
-		/// Subscription message is a byte '1' (for subscriptions) or byte '0' (for unsubscriptions) followed by the subscription body.
-		/// </remarks>
-		XSUB,
+        /// <summary>
+        /// XSubscriber
+        /// </summary>
+        /// <remarks>
+        /// Subscription message is a byte '1' (for subscriptions) or byte '0' (for unsubscriptions) followed by the subscription body.
+        /// </remarks>
+        XSUB,
 
-		/// <summary>
-		/// Stream
-		/// </summary>
-		/// <remarks>
-		/// </remarks>
-		STREAM
-	}
+        /// <summary>
+        /// Stream
+        /// </summary>
+        /// <remarks>
+        /// </remarks>
+        STREAM
+    }
 }

+ 429 - 420
dotnet/Library/Sers/Sers.CL/Zmq/FullDuplex/Sers.CL.Zmq.FullDuplex/Zmq/zmq.cs

@@ -1,34 +1,34 @@
 namespace Sers.CL.Zmq.FullDuplex.Zmq
-{
-	using System;
-	using System.Runtime.InteropServices;
-
-	public static unsafe class zmq
-	{
-		private const string __Internal = "__Internal";
-
-		private const CallingConvention CCCdecl = CallingConvention.Cdecl;
-
-		// Use a const for the library name
-		private const string LibraryName = "libzmq";
-
-		// Hold a handle to the static instance
-		//private static readonly UnmanagedLibrary NativeLib;
-
-		// From zmq.h (v3):
-		// typedef struct {unsigned char _ [32];} zmq_msg_t;
-		private static readonly int sizeof_zmq_msg_t_v3 = 32 * Marshal.SizeOf(typeof(byte));
-
-		// From zmq.h (not v4, but v4.2 and later):
-		// typedef struct zmq_msg_t {unsigned char _ [64];} zmq_msg_t;
-		private static readonly int sizeof_zmq_msg_t_v4 = 64 * Marshal.SizeOf(typeof(byte));
-
-		public static readonly int sizeof_zmq_msg_t = sizeof_zmq_msg_t_v4;
-
-		// The static constructor prepares static readonly fields
-		static zmq()
-		{
-
+{
+    using System;
+    using System.Runtime.InteropServices;
+
+    public static unsafe class zmq
+    {
+        private const string __Internal = "__Internal";
+
+        private const CallingConvention CCCdecl = CallingConvention.Cdecl;
+
+        // Use a const for the library name
+        private const string LibraryName = "libzmq";
+
+        // Hold a handle to the static instance
+        //private static readonly UnmanagedLibrary NativeLib;
+
+        // From zmq.h (v3):
+        // typedef struct {unsigned char _ [32];} zmq_msg_t;
+        private static readonly int sizeof_zmq_msg_t_v3 = 32 * Marshal.SizeOf(typeof(byte));
+
+        // From zmq.h (not v4, but v4.2 and later):
+        // typedef struct zmq_msg_t {unsigned char _ [64];} zmq_msg_t;
+        private static readonly int sizeof_zmq_msg_t_v4 = 64 * Marshal.SizeOf(typeof(byte));
+
+        public static readonly int sizeof_zmq_msg_t = sizeof_zmq_msg_t_v4;
+
+        // The static constructor prepares static readonly fields
+        static zmq()
+        {
+
 #if !NETSTANDARD && !NETCORE
 			// (0) Initialize Library handle
 			NativeLib = Platform.LoadUnmanagedLibrary(LibraryName);
@@ -36,392 +36,401 @@
 			// (1) Initialize Platform information 
 			Platform.SetupImplementation(typeof(zmq));
 #endif
-
-			// Set once LibVersion to libversion()
-			int major, minor, patch;
-			version(out major, out minor, out patch);
-			LibraryVersion = new Version(major, minor, patch);
-
-			// Trigger static constructor
-            // TODO this is also done in the static initializer of ZError. Can this be unified?
-			//var noSym = ZSymbol.None;
-
-			if (major >= 4)
-			{
-				// Current Version 4
-
-				// Use default delegate settings from field initializers.
-				// "Compatibility" is done by "disabling" old methods, or "redirecting" to new methods,
-				// so the developer is forced to work against the latest API
-
-				if (minor == 0)
-				{
-					sizeof_zmq_msg_t = sizeof_zmq_msg_t_v3;
-				}
-			}
-			else if (major >= 3)
-			{
-				// Backwards compatibility for v3
-
-				sizeof_zmq_msg_t = sizeof_zmq_msg_t_v3;
-
-				zmq.ctx_shutdown = (ctxPtr) 
-					=> { throw VersionNotSupported("zmq_ctx_shutdown", "v4"); };
-				zmq.msg_gets = (msgPtr, propertyPtr) 
-					=> { throw VersionNotSupported("zmq_msg_gets", "v4"); };
-				zmq.has = (capabilityPtr) 
-					=> { throw VersionNotSupported("zmq_has", "v4"); };
-				zmq.proxy_steerable = (frontendPtr, backendPtr, capturePtr, controlPtr)
-					=> { throw VersionNotSupported("zmq_proxy_steerable", "v4"); };
-				zmq.curve_keypair = (z85_public_key, z85_secret_key) 
-					=> { throw VersionNotSupported("zmq_curve_keypair", "v4"); };
-				zmq.z85_encode = (dest, data, size) 
-					=> { throw VersionNotSupported("zmq_z85_encode", "v4"); };
-				zmq.z85_decode = (dest, data) 
-					=> { throw VersionNotSupported("zmq_z85_decode", "v4"); };
-
-				if (!Platform.Is__Internal) {
-					zmq.ctx_term = zmq.zmq_term;
-				}
-				else {
-					zmq.ctx_term = zmq.zmq_term__Internal;
-				}
-			}
-			else 
-			{ 
-				throw VersionNotSupported(null, ">= v3");
-			}
-		}
-
-		private static NotSupportedException VersionNotSupported(string methodName, string requiredVersion)
-		{
-			return new NotSupportedException(
-				string.Format(
-					"{0}libzmq version not supported. Required version {1}",
-					methodName == null ? string.Empty : methodName + ": ",
-					requiredVersion));
-		}
-
-		// (2) Declare privately the extern entry point
-		[DllImport(LibraryName, EntryPoint = "zmq_version", CallingConvention = CCCdecl)]
-		private static extern void zmq_version(out int major, out int minor, out int patch);
-		[DllImport(__Internal, EntryPoint = "zmq_version", CallingConvention = CCCdecl)]
-		private static extern void zmq_version__Internal(out int major, out int minor, out int patch);
-
-		// (3) Describe the extern function using a delegate
-		public delegate void zmq_version_delegate(out int major, out int minor, out int patch);
-
-		// (4) Save and return the managed delegate to the unmanaged function
-		//     This static readonly field definition allows to be 
-		//     initialized and possibly redirected by the static constructor.
-		//
-		//     By default this is set to the extern function declaration,
-		//     it may be set to the __Internal extern function declaration.
-		public static readonly zmq_version_delegate version = zmq_version;
-
-		public static readonly Version LibraryVersion;
-
-		/* Deprecated. Use zmq_ctx_new instead.
+
+            // Set once LibVersion to libversion()
+            int major, minor, patch;
+            version(out major, out minor, out patch);
+            LibraryVersion = new Version(major, minor, patch);
+
+            // Trigger static constructor
+            // TODO this is also done in the static initializer of ZError. Can this be unified?
+            //var noSym = ZSymbol.None;
+
+            if (major >= 4)
+            {
+                // Current Version 4
+
+                // Use default delegate settings from field initializers.
+                // "Compatibility" is done by "disabling" old methods, or "redirecting" to new methods,
+                // so the developer is forced to work against the latest API
+
+                if (minor == 0)
+                {
+                    sizeof_zmq_msg_t = sizeof_zmq_msg_t_v3;
+                }
+            }
+            else if (major >= 3)
+            {
+                // Backwards compatibility for v3
+
+                sizeof_zmq_msg_t = sizeof_zmq_msg_t_v3;
+
+                zmq.ctx_shutdown = (ctxPtr)
+                    =>
+                { throw VersionNotSupported("zmq_ctx_shutdown", "v4"); };
+                zmq.msg_gets = (msgPtr, propertyPtr)
+                    =>
+                { throw VersionNotSupported("zmq_msg_gets", "v4"); };
+                zmq.has = (capabilityPtr)
+                    =>
+                { throw VersionNotSupported("zmq_has", "v4"); };
+                zmq.proxy_steerable = (frontendPtr, backendPtr, capturePtr, controlPtr)
+                    =>
+                { throw VersionNotSupported("zmq_proxy_steerable", "v4"); };
+                zmq.curve_keypair = (z85_public_key, z85_secret_key)
+                    =>
+                { throw VersionNotSupported("zmq_curve_keypair", "v4"); };
+                zmq.z85_encode = (dest, data, size)
+                    =>
+                { throw VersionNotSupported("zmq_z85_encode", "v4"); };
+                zmq.z85_decode = (dest, data)
+                    =>
+                { throw VersionNotSupported("zmq_z85_decode", "v4"); };
+
+                if (!Platform.Is__Internal)
+                {
+                    zmq.ctx_term = zmq.zmq_term;
+                }
+                else
+                {
+                    zmq.ctx_term = zmq.zmq_term__Internal;
+                }
+            }
+            else
+            {
+                throw VersionNotSupported(null, ">= v3");
+            }
+        }
+
+        private static NotSupportedException VersionNotSupported(string methodName, string requiredVersion)
+        {
+            return new NotSupportedException(
+                string.Format(
+                    "{0}libzmq version not supported. Required version {1}",
+                    methodName == null ? string.Empty : methodName + ": ",
+                    requiredVersion));
+        }
+
+        // (2) Declare privately the extern entry point
+        [DllImport(LibraryName, EntryPoint = "zmq_version", CallingConvention = CCCdecl)]
+        private static extern void zmq_version(out int major, out int minor, out int patch);
+        [DllImport(__Internal, EntryPoint = "zmq_version", CallingConvention = CCCdecl)]
+        private static extern void zmq_version__Internal(out int major, out int minor, out int patch);
+
+        // (3) Describe the extern function using a delegate
+        public delegate void zmq_version_delegate(out int major, out int minor, out int patch);
+
+        // (4) Save and return the managed delegate to the unmanaged function
+        //     This static readonly field definition allows to be 
+        //     initialized and possibly redirected by the static constructor.
+        //
+        //     By default this is set to the extern function declaration,
+        //     it may be set to the __Internal extern function declaration.
+        public static readonly zmq_version_delegate version = zmq_version;
+
+        public static readonly Version LibraryVersion;
+
+        /* Deprecated. Use zmq_ctx_new instead.
 		[DllImport(LibraryName, EntryPoint = "zmq_init", CallingConvention = CCCdecl)]
-		private static extern IntPtr init(int io_threads); /**/
-
-		[DllImport(LibraryName, EntryPoint = "zmq_ctx_new", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_ctx_new();
-		[DllImport(__Internal, EntryPoint = "zmq_ctx_new", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_ctx_new__Internal();
-		public delegate IntPtr zmq_ctx_new_delegate();
-		public static readonly zmq_ctx_new_delegate ctx_new = zmq_ctx_new;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_ctx_get", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_ctx_get(IntPtr context, Int32 option);
-		[DllImport(__Internal, EntryPoint = "zmq_ctx_get", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_ctx_get__Internal(IntPtr context, Int32 option);
-		public delegate Int32 zmq_ctx_get_delegate(IntPtr context, Int32 option);
-		public static readonly zmq_ctx_get_delegate ctx_get = zmq_ctx_get;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_ctx_set", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_ctx_set(IntPtr context, Int32 option, Int32 optval);
-		[DllImport(__Internal, EntryPoint = "zmq_ctx_set", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_ctx_set__Internal(IntPtr context, Int32 option, Int32 optval);
-		public delegate Int32 zmq_ctx_set_delegate(IntPtr context, Int32 option, Int32 optval);
-		public static readonly zmq_ctx_set_delegate ctx_set = zmq_ctx_set;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_ctx_shutdown", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_ctx_shutdown(IntPtr context);
-		[DllImport(__Internal, EntryPoint = "zmq_ctx_shutdown", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_ctx_shutdown__Internal(IntPtr context);
-		public delegate Int32 zmq_ctx_shutdown_delegate(IntPtr context);
-		public static readonly zmq_ctx_shutdown_delegate ctx_shutdown = zmq_ctx_shutdown;
-
-		/* Deprecated. Use zmq_ctx_term instead.
+		private static extern IntPtr init(int io_threads); /**/
+
+        [DllImport(LibraryName, EntryPoint = "zmq_ctx_new", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_ctx_new();
+        [DllImport(__Internal, EntryPoint = "zmq_ctx_new", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_ctx_new__Internal();
+        public delegate IntPtr zmq_ctx_new_delegate();
+        public static readonly zmq_ctx_new_delegate ctx_new = zmq_ctx_new;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_ctx_get", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_ctx_get(IntPtr context, Int32 option);
+        [DllImport(__Internal, EntryPoint = "zmq_ctx_get", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_ctx_get__Internal(IntPtr context, Int32 option);
+        public delegate Int32 zmq_ctx_get_delegate(IntPtr context, Int32 option);
+        public static readonly zmq_ctx_get_delegate ctx_get = zmq_ctx_get;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_ctx_set", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_ctx_set(IntPtr context, Int32 option, Int32 optval);
+        [DllImport(__Internal, EntryPoint = "zmq_ctx_set", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_ctx_set__Internal(IntPtr context, Int32 option, Int32 optval);
+        public delegate Int32 zmq_ctx_set_delegate(IntPtr context, Int32 option, Int32 optval);
+        public static readonly zmq_ctx_set_delegate ctx_set = zmq_ctx_set;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_ctx_shutdown", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_ctx_shutdown(IntPtr context);
+        [DllImport(__Internal, EntryPoint = "zmq_ctx_shutdown", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_ctx_shutdown__Internal(IntPtr context);
+        public delegate Int32 zmq_ctx_shutdown_delegate(IntPtr context);
+        public static readonly zmq_ctx_shutdown_delegate ctx_shutdown = zmq_ctx_shutdown;
+
+        /* Deprecated. Use zmq_ctx_term instead.
 		[DllImport(LibraryName, CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_term(IntPtr context); /**/
-
-		/* Deprecated. Use zmq_ctx_term instead. */
-		[DllImport(LibraryName, EntryPoint = "zmq_term", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_term(IntPtr context);
-		[DllImport(__Internal, EntryPoint = "zmq_term", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_term__Internal(IntPtr context);
-
-		[DllImport(LibraryName, EntryPoint = "zmq_ctx_term", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_ctx_term(IntPtr context);
-		[DllImport(__Internal, EntryPoint = "zmq_ctx_term", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_ctx_term__Internal(IntPtr context);
-		public delegate Int32 zmq_ctx_term_delegate(IntPtr context);
-		public static readonly zmq_ctx_term_delegate ctx_term = zmq_ctx_term;
-
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_init", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_init(IntPtr msg);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_init", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_init__Internal(IntPtr msg);
-		public delegate Int32 zmq_msg_init_delegate(IntPtr msg);
-		public static readonly zmq_msg_init_delegate msg_init = zmq_msg_init;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_init_size", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_init_size(IntPtr msg, Int32 size);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_init_size", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_init_size__Internal(IntPtr msg, Int32 size);
-		public delegate Int32 zmq_msg_init_size_delegate(IntPtr msg, Int32 size);
-		public static readonly zmq_msg_init_size_delegate msg_init_size = zmq_msg_init_size;
-
-		[UnmanagedFunctionPointer(CCCdecl)]
-		public delegate void FreeMessageDataDelegate(IntPtr data, IntPtr hint);
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_init_data", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_init_data(IntPtr msg, IntPtr data, Int32 size, FreeMessageDataDelegate ffn, IntPtr hint);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_init_data", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_init_data__Internal(IntPtr msg, IntPtr data, Int32 size, FreeMessageDataDelegate ffn, IntPtr hint);
-		public delegate Int32 zmq_msg_init_data_delegate(IntPtr msg, IntPtr data, Int32 size, FreeMessageDataDelegate ffn, IntPtr hint);
-		public static readonly zmq_msg_init_data_delegate msg_init_data = zmq_msg_init_data;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_send", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_send(IntPtr msg, IntPtr socket, Int32 flags);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_send", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_send__Internal(IntPtr msg, IntPtr socket, Int32 flags);
-		public delegate Int32 zmq_msg_send_delegate(IntPtr msg, IntPtr socket, Int32 flags);
-		public static readonly zmq_msg_send_delegate msg_send = zmq_msg_send;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_recv", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_recv(IntPtr msg, IntPtr socket, Int32 flags);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_recv", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_recv__Internal(IntPtr msg, IntPtr socket, Int32 flags);
-		public delegate Int32 zmq_msg_recv_delegate(IntPtr msg, IntPtr socket, Int32 flags);
-		public static readonly zmq_msg_recv_delegate msg_recv = zmq_msg_recv;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_close", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_close(IntPtr msg);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_close", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_close__Internal(IntPtr msg);
-		public delegate Int32 zmq_msg_close_delegate(IntPtr msg);
-		public static readonly zmq_msg_close_delegate msg_close = zmq_msg_close;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_data", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_msg_data(IntPtr msg);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_data", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_msg_data__Internal(IntPtr msg);
-		public delegate IntPtr zmq_msg_data_delegate(IntPtr msg);
-		public static readonly zmq_msg_data_delegate msg_data = zmq_msg_data;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_size", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_size(IntPtr msg);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_size", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_size__Internal(IntPtr msg);
-		public delegate Int32 zmq_msg_size_delegate(IntPtr msg);
-		public static readonly zmq_msg_size_delegate msg_size = zmq_msg_size;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_more", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_more(IntPtr msg);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_more", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_more__Internal(IntPtr msg);
-		public delegate Int32 zmq_msg_more_delegate(IntPtr msg);
-		public static readonly zmq_msg_more_delegate msg_more = zmq_msg_more;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_gets", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_msg_gets(IntPtr msg, IntPtr property);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_gets", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_msg_gets__Internal(IntPtr msg, IntPtr property);
-		public delegate IntPtr zmq_msg_gets_delegate(IntPtr msg, IntPtr property);
-		public static readonly zmq_msg_gets_delegate msg_gets = zmq_msg_gets;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_get", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_get(IntPtr msg, Int32 property);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_get", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_get__Internal(IntPtr msg, Int32 property);
-		public delegate Int32 zmq_msg_get_delegate(IntPtr msg, Int32 property);
-		public static readonly zmq_msg_get_delegate msg_get = zmq_msg_get;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_set", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_set(IntPtr msg, Int32 property, Int32 value);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_set", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_set__Internal(IntPtr msg, Int32 property, Int32 value);
-		public delegate Int32 zmq_msg_set_delegate(IntPtr msg, Int32 property, Int32 value);
-		public static readonly zmq_msg_set_delegate msg_set = zmq_msg_set;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_copy", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_copy(IntPtr dest, IntPtr src);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_copy", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_copy__Internal(IntPtr dest, IntPtr src);
-		public delegate Int32 zmq_msg_copy_delegate(IntPtr dest, IntPtr src);
-		public static readonly zmq_msg_copy_delegate msg_copy = zmq_msg_copy;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_move", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_move(IntPtr dest, IntPtr src);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_move", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_move__Internal(IntPtr dest, IntPtr src);
-		public delegate Int32 zmq_msg_move_delegate(IntPtr dest, IntPtr src);
-		public static readonly zmq_msg_move_delegate msg_move = zmq_msg_move;
-
-
-		[DllImport(LibraryName, EntryPoint = "zmq_socket", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_socket(IntPtr context, Int32 type);
-		[DllImport(__Internal, EntryPoint = "zmq_socket", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_socket__Internal(IntPtr context, Int32 type);
-		public delegate IntPtr zmq_socket_delegate(IntPtr context, Int32 type);
-		public static readonly zmq_socket_delegate socket = zmq_socket;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_close", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_close(IntPtr socket);
-		[DllImport(__Internal, EntryPoint = "zmq_close", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_close__Internal(IntPtr socket);
-		public delegate Int32 zmq_close_delegate(IntPtr socket);
-		public static readonly zmq_close_delegate close = zmq_close;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_getsockopt", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_getsockopt(IntPtr socket, Int32 option_name, IntPtr option_value, IntPtr option_len);
-		[DllImport(__Internal, EntryPoint = "zmq_getsockopt", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_getsockopt__Internal(IntPtr socket, Int32 option_name, IntPtr option_value, IntPtr option_len);
-		public delegate Int32 zmq_getsockopt_delegate(IntPtr socket, Int32 option_name, IntPtr option_value, IntPtr option_len);
-		public static readonly zmq_getsockopt_delegate getsockopt = zmq_getsockopt;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_setsockopt", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_setsockopt(IntPtr socket, Int32 option_name, IntPtr option_value, Int32 option_len);
-		[DllImport(__Internal, EntryPoint = "zmq_setsockopt", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_setsockopt__Internal(IntPtr socket, Int32 option_name, IntPtr option_value, Int32 option_len);
-		public delegate Int32 zmq_setsockopt_delegate(IntPtr socket, Int32 option_name, IntPtr option_value, Int32 option_len);
-		public static readonly zmq_setsockopt_delegate setsockopt = zmq_setsockopt;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_bind", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_bind(IntPtr socket, string endpoint);
-		[DllImport(__Internal, EntryPoint = "zmq_bind", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_bind__Internal(IntPtr socket, string endpoint);
-		public delegate Int32 zmq_bind_delegate(IntPtr socket, string endpoint);
-		public static readonly zmq_bind_delegate bind = zmq_bind;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_unbind", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_unbind(IntPtr socket, IntPtr endpoint);
-		[DllImport(__Internal, EntryPoint = "zmq_unbind", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_unbind__Internal(IntPtr socket, IntPtr endpoint);
-		public delegate Int32 zmq_unbind_delegate(IntPtr socket, IntPtr endpoint);
-		public static readonly zmq_unbind_delegate unbind = zmq_unbind;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_connect", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_connect(IntPtr socket, string endpoint);
-		[DllImport(__Internal, EntryPoint = "zmq_connect", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_connect__Internal(IntPtr socket, string endpoint);
-		public delegate Int32 zmq_connect_delegate(IntPtr socket, string endpoint);
-		public static readonly zmq_connect_delegate connect = zmq_connect;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_disconnect", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_disconnect(IntPtr socket, string endpoint);
-		[DllImport(__Internal, EntryPoint = "zmq_disconnect", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_disconnect__Internal(IntPtr socket, string endpoint);
-		public delegate Int32 zmq_disconnect_delegate(IntPtr socket, string endpoint);
-		public static readonly zmq_disconnect_delegate disconnect = zmq_disconnect;
-
-		// Using void* to be liberal for zmq_pollitem_windows_t and _posix_t
-		[DllImport(LibraryName, EntryPoint = "zmq_poll", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_poll(void* items, Int32 numItems, long timeout);
-		[DllImport(__Internal, EntryPoint = "zmq_poll", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_poll__Internal(void* items, Int32 numItems, long timeout);
-		// private static extern Int32 zmq_poll(IntPtr items, Int32 numItems, long timeout);
-		public delegate Int32 zmq_poll_delegate(void* items, Int32 numItems, long timeout);
-		public static readonly zmq_poll_delegate poll = zmq_poll;
-
-
-		[DllImport(LibraryName, EntryPoint = "zmq_send", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_send(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
-		[DllImport(__Internal, EntryPoint = "zmq_send", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_send__Internal(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
-		public delegate Int32 zmq_send_delegate(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
-		public static readonly zmq_send_delegate send = zmq_send;
-
-		// [DllImport(LibraryName, CallingConvention = CCCdecl)]
-		// private static extern Int32 zmq_send_const(IntPtr socket, IntPtr buf, Int32 size, Int32 flags);
-
-		[DllImport(LibraryName, EntryPoint = "zmq_recv", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_recv(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
-		[DllImport(__Internal, EntryPoint = "zmq_recv", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_recv__Internal(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
-		public delegate Int32 zmq_recv_delegate(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
-		public static readonly zmq_recv_delegate recv = zmq_recv;
-
-
-		[DllImport(LibraryName, EntryPoint = "zmq_has", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_has(IntPtr capability);
-		[DllImport(__Internal, EntryPoint = "zmq_has", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_has__Internal(IntPtr capability);
-		public delegate Int32 zmq_has_delegate(IntPtr capability);
-		public static readonly zmq_has_delegate has = zmq_has;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_socket_monitor", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_socket_monitor(IntPtr socket, IntPtr endpoint, Int32 events);
-		[DllImport(__Internal, EntryPoint = "zmq_socket_monitor", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_socket_monitor__Internal(IntPtr socket, IntPtr endpoint, Int32 events);
-		public delegate Int32 zmq_socket_monitor_delegate(IntPtr socket, IntPtr endpoint, Int32 events);
-		public static readonly zmq_socket_monitor_delegate socket_monitor = zmq_socket_monitor;
-
-
-		[DllImport(LibraryName, EntryPoint = "zmq_proxy", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_proxy(IntPtr frontend, IntPtr backend, IntPtr capture);
-		[DllImport(__Internal, EntryPoint = "zmq_proxy", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_proxy__Internal(IntPtr frontend, IntPtr backend, IntPtr capture);
-		public delegate Int32 zmq_proxy_delegate(IntPtr frontend, IntPtr backend, IntPtr capture);
-		public static readonly zmq_proxy_delegate proxy = zmq_proxy;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_proxy_steerable", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_proxy_steerable(IntPtr frontend, IntPtr backend, IntPtr capture, IntPtr control);
-		[DllImport(__Internal, EntryPoint = "zmq_proxy_steerable", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_proxy_steerable__Internal(IntPtr frontend, IntPtr backend, IntPtr capture, IntPtr control);
-		public delegate Int32 zmq_proxy_steerable_delegate(IntPtr frontend, IntPtr backend, IntPtr capture, IntPtr control);
-		public static readonly zmq_proxy_steerable_delegate proxy_steerable = zmq_proxy_steerable;
-
-
-		[DllImport(LibraryName, EntryPoint = "zmq_curve_keypair", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_curve_keypair(IntPtr z85_public_key, IntPtr z85_secret_key);
-		[DllImport(__Internal, EntryPoint = "zmq_curve_keypair", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_curve_keypair__Internal(IntPtr z85_public_key, IntPtr z85_secret_key);
-		public delegate Int32 zmq_curve_keypair_delegate(IntPtr z85_public_key, IntPtr z85_secret_key);
-		public static readonly zmq_curve_keypair_delegate curve_keypair = zmq_curve_keypair;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_z85_encode", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_z85_encode(IntPtr dest, IntPtr data, Int32 size);
-		[DllImport(__Internal, EntryPoint = "zmq_z85_encode", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_z85_encode__Internal(IntPtr dest, IntPtr data, Int32 size);
-		public delegate IntPtr zmq_z85_encode_delegate(IntPtr dest, IntPtr data, Int32 size);
-		public static readonly zmq_z85_encode_delegate z85_encode = zmq_z85_encode;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_z85_decode", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_z85_decode(IntPtr dest, IntPtr data);
-		[DllImport(__Internal, EntryPoint = "zmq_z85_decode", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_z85_decode__Internal(IntPtr dest, IntPtr data);
-		public delegate IntPtr zmq_z85_decode_delegate(IntPtr dest, IntPtr data);
-		public static readonly zmq_z85_decode_delegate z85_decode = zmq_z85_decode;
-
-
-		[DllImport(LibraryName, EntryPoint = "zmq_errno", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_errno();
-		[DllImport(__Internal, EntryPoint = "zmq_errno", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_errno__Internal();
-		public delegate Int32 zmq_errno_delegate();
-        public static readonly zmq_errno_delegate errno = zmq_errno;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_strerror", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_strerror(int errnum);
-		[DllImport(__Internal, EntryPoint = "zmq_strerror", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_strerror__Internal(int errnum);
-		public delegate IntPtr zmq_strerror_delegate(int errnum);
-		public static readonly zmq_strerror_delegate strerror = zmq_strerror;
+		private static extern Int32 zmq_term(IntPtr context); /**/
+
+        /* Deprecated. Use zmq_ctx_term instead. */
+        [DllImport(LibraryName, EntryPoint = "zmq_term", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_term(IntPtr context);
+        [DllImport(__Internal, EntryPoint = "zmq_term", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_term__Internal(IntPtr context);
+
+        [DllImport(LibraryName, EntryPoint = "zmq_ctx_term", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_ctx_term(IntPtr context);
+        [DllImport(__Internal, EntryPoint = "zmq_ctx_term", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_ctx_term__Internal(IntPtr context);
+        public delegate Int32 zmq_ctx_term_delegate(IntPtr context);
+        public static readonly zmq_ctx_term_delegate ctx_term = zmq_ctx_term;
+
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_init", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_init(IntPtr msg);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_init", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_init__Internal(IntPtr msg);
+        public delegate Int32 zmq_msg_init_delegate(IntPtr msg);
+        public static readonly zmq_msg_init_delegate msg_init = zmq_msg_init;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_init_size", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_init_size(IntPtr msg, Int32 size);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_init_size", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_init_size__Internal(IntPtr msg, Int32 size);
+        public delegate Int32 zmq_msg_init_size_delegate(IntPtr msg, Int32 size);
+        public static readonly zmq_msg_init_size_delegate msg_init_size = zmq_msg_init_size;
+
+        [UnmanagedFunctionPointer(CCCdecl)]
+        public delegate void FreeMessageDataDelegate(IntPtr data, IntPtr hint);
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_init_data", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_init_data(IntPtr msg, IntPtr data, Int32 size, FreeMessageDataDelegate ffn, IntPtr hint);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_init_data", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_init_data__Internal(IntPtr msg, IntPtr data, Int32 size, FreeMessageDataDelegate ffn, IntPtr hint);
+        public delegate Int32 zmq_msg_init_data_delegate(IntPtr msg, IntPtr data, Int32 size, FreeMessageDataDelegate ffn, IntPtr hint);
+        public static readonly zmq_msg_init_data_delegate msg_init_data = zmq_msg_init_data;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_send", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_send(IntPtr msg, IntPtr socket, Int32 flags);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_send", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_send__Internal(IntPtr msg, IntPtr socket, Int32 flags);
+        public delegate Int32 zmq_msg_send_delegate(IntPtr msg, IntPtr socket, Int32 flags);
+        public static readonly zmq_msg_send_delegate msg_send = zmq_msg_send;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_recv", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_recv(IntPtr msg, IntPtr socket, Int32 flags);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_recv", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_recv__Internal(IntPtr msg, IntPtr socket, Int32 flags);
+        public delegate Int32 zmq_msg_recv_delegate(IntPtr msg, IntPtr socket, Int32 flags);
+        public static readonly zmq_msg_recv_delegate msg_recv = zmq_msg_recv;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_close", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_close(IntPtr msg);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_close", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_close__Internal(IntPtr msg);
+        public delegate Int32 zmq_msg_close_delegate(IntPtr msg);
+        public static readonly zmq_msg_close_delegate msg_close = zmq_msg_close;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_data", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_msg_data(IntPtr msg);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_data", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_msg_data__Internal(IntPtr msg);
+        public delegate IntPtr zmq_msg_data_delegate(IntPtr msg);
+        public static readonly zmq_msg_data_delegate msg_data = zmq_msg_data;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_size", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_size(IntPtr msg);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_size", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_size__Internal(IntPtr msg);
+        public delegate Int32 zmq_msg_size_delegate(IntPtr msg);
+        public static readonly zmq_msg_size_delegate msg_size = zmq_msg_size;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_more", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_more(IntPtr msg);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_more", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_more__Internal(IntPtr msg);
+        public delegate Int32 zmq_msg_more_delegate(IntPtr msg);
+        public static readonly zmq_msg_more_delegate msg_more = zmq_msg_more;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_gets", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_msg_gets(IntPtr msg, IntPtr property);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_gets", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_msg_gets__Internal(IntPtr msg, IntPtr property);
+        public delegate IntPtr zmq_msg_gets_delegate(IntPtr msg, IntPtr property);
+        public static readonly zmq_msg_gets_delegate msg_gets = zmq_msg_gets;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_get", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_get(IntPtr msg, Int32 property);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_get", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_get__Internal(IntPtr msg, Int32 property);
+        public delegate Int32 zmq_msg_get_delegate(IntPtr msg, Int32 property);
+        public static readonly zmq_msg_get_delegate msg_get = zmq_msg_get;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_set", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_set(IntPtr msg, Int32 property, Int32 value);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_set", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_set__Internal(IntPtr msg, Int32 property, Int32 value);
+        public delegate Int32 zmq_msg_set_delegate(IntPtr msg, Int32 property, Int32 value);
+        public static readonly zmq_msg_set_delegate msg_set = zmq_msg_set;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_copy", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_copy(IntPtr dest, IntPtr src);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_copy", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_copy__Internal(IntPtr dest, IntPtr src);
+        public delegate Int32 zmq_msg_copy_delegate(IntPtr dest, IntPtr src);
+        public static readonly zmq_msg_copy_delegate msg_copy = zmq_msg_copy;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_move", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_move(IntPtr dest, IntPtr src);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_move", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_move__Internal(IntPtr dest, IntPtr src);
+        public delegate Int32 zmq_msg_move_delegate(IntPtr dest, IntPtr src);
+        public static readonly zmq_msg_move_delegate msg_move = zmq_msg_move;
+
+
+        [DllImport(LibraryName, EntryPoint = "zmq_socket", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_socket(IntPtr context, Int32 type);
+        [DllImport(__Internal, EntryPoint = "zmq_socket", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_socket__Internal(IntPtr context, Int32 type);
+        public delegate IntPtr zmq_socket_delegate(IntPtr context, Int32 type);
+        public static readonly zmq_socket_delegate socket = zmq_socket;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_close", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_close(IntPtr socket);
+        [DllImport(__Internal, EntryPoint = "zmq_close", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_close__Internal(IntPtr socket);
+        public delegate Int32 zmq_close_delegate(IntPtr socket);
+        public static readonly zmq_close_delegate close = zmq_close;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_getsockopt", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_getsockopt(IntPtr socket, Int32 option_name, IntPtr option_value, IntPtr option_len);
+        [DllImport(__Internal, EntryPoint = "zmq_getsockopt", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_getsockopt__Internal(IntPtr socket, Int32 option_name, IntPtr option_value, IntPtr option_len);
+        public delegate Int32 zmq_getsockopt_delegate(IntPtr socket, Int32 option_name, IntPtr option_value, IntPtr option_len);
+        public static readonly zmq_getsockopt_delegate getsockopt = zmq_getsockopt;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_setsockopt", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_setsockopt(IntPtr socket, Int32 option_name, IntPtr option_value, Int32 option_len);
+        [DllImport(__Internal, EntryPoint = "zmq_setsockopt", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_setsockopt__Internal(IntPtr socket, Int32 option_name, IntPtr option_value, Int32 option_len);
+        public delegate Int32 zmq_setsockopt_delegate(IntPtr socket, Int32 option_name, IntPtr option_value, Int32 option_len);
+        public static readonly zmq_setsockopt_delegate setsockopt = zmq_setsockopt;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_bind", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_bind(IntPtr socket, string endpoint);
+        [DllImport(__Internal, EntryPoint = "zmq_bind", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_bind__Internal(IntPtr socket, string endpoint);
+        public delegate Int32 zmq_bind_delegate(IntPtr socket, string endpoint);
+        public static readonly zmq_bind_delegate bind = zmq_bind;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_unbind", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_unbind(IntPtr socket, IntPtr endpoint);
+        [DllImport(__Internal, EntryPoint = "zmq_unbind", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_unbind__Internal(IntPtr socket, IntPtr endpoint);
+        public delegate Int32 zmq_unbind_delegate(IntPtr socket, IntPtr endpoint);
+        public static readonly zmq_unbind_delegate unbind = zmq_unbind;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_connect", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_connect(IntPtr socket, string endpoint);
+        [DllImport(__Internal, EntryPoint = "zmq_connect", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_connect__Internal(IntPtr socket, string endpoint);
+        public delegate Int32 zmq_connect_delegate(IntPtr socket, string endpoint);
+        public static readonly zmq_connect_delegate connect = zmq_connect;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_disconnect", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_disconnect(IntPtr socket, string endpoint);
+        [DllImport(__Internal, EntryPoint = "zmq_disconnect", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_disconnect__Internal(IntPtr socket, string endpoint);
+        public delegate Int32 zmq_disconnect_delegate(IntPtr socket, string endpoint);
+        public static readonly zmq_disconnect_delegate disconnect = zmq_disconnect;
+
+        // Using void* to be liberal for zmq_pollitem_windows_t and _posix_t
+        [DllImport(LibraryName, EntryPoint = "zmq_poll", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_poll(void* items, Int32 numItems, long timeout);
+        [DllImport(__Internal, EntryPoint = "zmq_poll", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_poll__Internal(void* items, Int32 numItems, long timeout);
+        // private static extern Int32 zmq_poll(IntPtr items, Int32 numItems, long timeout);
+        public delegate Int32 zmq_poll_delegate(void* items, Int32 numItems, long timeout);
+        public static readonly zmq_poll_delegate poll = zmq_poll;
+
+
+        [DllImport(LibraryName, EntryPoint = "zmq_send", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_send(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
+        [DllImport(__Internal, EntryPoint = "zmq_send", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_send__Internal(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
+        public delegate Int32 zmq_send_delegate(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
+        public static readonly zmq_send_delegate send = zmq_send;
+
+        // [DllImport(LibraryName, CallingConvention = CCCdecl)]
+        // private static extern Int32 zmq_send_const(IntPtr socket, IntPtr buf, Int32 size, Int32 flags);
+
+        [DllImport(LibraryName, EntryPoint = "zmq_recv", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_recv(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
+        [DllImport(__Internal, EntryPoint = "zmq_recv", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_recv__Internal(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
+        public delegate Int32 zmq_recv_delegate(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
+        public static readonly zmq_recv_delegate recv = zmq_recv;
+
+
+        [DllImport(LibraryName, EntryPoint = "zmq_has", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_has(IntPtr capability);
+        [DllImport(__Internal, EntryPoint = "zmq_has", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_has__Internal(IntPtr capability);
+        public delegate Int32 zmq_has_delegate(IntPtr capability);
+        public static readonly zmq_has_delegate has = zmq_has;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_socket_monitor", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_socket_monitor(IntPtr socket, IntPtr endpoint, Int32 events);
+        [DllImport(__Internal, EntryPoint = "zmq_socket_monitor", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_socket_monitor__Internal(IntPtr socket, IntPtr endpoint, Int32 events);
+        public delegate Int32 zmq_socket_monitor_delegate(IntPtr socket, IntPtr endpoint, Int32 events);
+        public static readonly zmq_socket_monitor_delegate socket_monitor = zmq_socket_monitor;
+
+
+        [DllImport(LibraryName, EntryPoint = "zmq_proxy", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_proxy(IntPtr frontend, IntPtr backend, IntPtr capture);
+        [DllImport(__Internal, EntryPoint = "zmq_proxy", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_proxy__Internal(IntPtr frontend, IntPtr backend, IntPtr capture);
+        public delegate Int32 zmq_proxy_delegate(IntPtr frontend, IntPtr backend, IntPtr capture);
+        public static readonly zmq_proxy_delegate proxy = zmq_proxy;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_proxy_steerable", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_proxy_steerable(IntPtr frontend, IntPtr backend, IntPtr capture, IntPtr control);
+        [DllImport(__Internal, EntryPoint = "zmq_proxy_steerable", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_proxy_steerable__Internal(IntPtr frontend, IntPtr backend, IntPtr capture, IntPtr control);
+        public delegate Int32 zmq_proxy_steerable_delegate(IntPtr frontend, IntPtr backend, IntPtr capture, IntPtr control);
+        public static readonly zmq_proxy_steerable_delegate proxy_steerable = zmq_proxy_steerable;
+
+
+        [DllImport(LibraryName, EntryPoint = "zmq_curve_keypair", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_curve_keypair(IntPtr z85_public_key, IntPtr z85_secret_key);
+        [DllImport(__Internal, EntryPoint = "zmq_curve_keypair", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_curve_keypair__Internal(IntPtr z85_public_key, IntPtr z85_secret_key);
+        public delegate Int32 zmq_curve_keypair_delegate(IntPtr z85_public_key, IntPtr z85_secret_key);
+        public static readonly zmq_curve_keypair_delegate curve_keypair = zmq_curve_keypair;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_z85_encode", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_z85_encode(IntPtr dest, IntPtr data, Int32 size);
+        [DllImport(__Internal, EntryPoint = "zmq_z85_encode", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_z85_encode__Internal(IntPtr dest, IntPtr data, Int32 size);
+        public delegate IntPtr zmq_z85_encode_delegate(IntPtr dest, IntPtr data, Int32 size);
+        public static readonly zmq_z85_encode_delegate z85_encode = zmq_z85_encode;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_z85_decode", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_z85_decode(IntPtr dest, IntPtr data);
+        [DllImport(__Internal, EntryPoint = "zmq_z85_decode", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_z85_decode__Internal(IntPtr dest, IntPtr data);
+        public delegate IntPtr zmq_z85_decode_delegate(IntPtr dest, IntPtr data);
+        public static readonly zmq_z85_decode_delegate z85_decode = zmq_z85_decode;
+
+
+        [DllImport(LibraryName, EntryPoint = "zmq_errno", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_errno();
+        [DllImport(__Internal, EntryPoint = "zmq_errno", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_errno__Internal();
+        public delegate Int32 zmq_errno_delegate();
+        public static readonly zmq_errno_delegate errno = zmq_errno;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_strerror", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_strerror(int errnum);
+        [DllImport(__Internal, EntryPoint = "zmq_strerror", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_strerror__Internal(int errnum);
+        public delegate IntPtr zmq_strerror_delegate(int errnum);
+        public static readonly zmq_strerror_delegate strerror = zmq_strerror;
 
 
 
@@ -441,8 +450,8 @@
         //        zmq.ThrowErrno(errno);
         //    }
         //}
- 
-        public static void ReceiveMessage(IntPtr socket, out byte[] byte_received,int flags=0)
+
+        public static void ReceiveMessage(IntPtr socket, out byte[] byte_received, int flags = 0)
         {
             zmq_msg_t* msgReceived = stackalloc zmq_msg_t[1];
 
@@ -485,12 +494,12 @@
         /// <returns></returns>
         public static void ThrowErrno(int errno)
         {
-            throw new Exception("zmq error:   errno-" +errno +"  err-" + ((ZError)errno));        
+            throw new Exception("zmq error:   errno-" + errno + "  err-" + ((ZError)errno));
         }
 
         public static void SendMessage(IntPtr socket, byte[] byte_send, int flags = 0)
         {
-            SendMessage(socket, byte_send,flags,0, byte_send.Length);
+            SendMessage(socket, byte_send, flags, 0, byte_send.Length);
         }
 
         public static void SendMessage(IntPtr socket, byte[] buffer, int flags, int offset, int count)
@@ -516,8 +525,8 @@
             //return true;
         }
 
-      
- 
+
+
 
         #endregion
 

+ 8 - 9
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/Sers.CL.ClrZmq.ThreadWait/DeliveryClient.cs

@@ -1,5 +1,4 @@
 using System;
-using System.Collections.Generic;
 using System.Threading;
 
 using Sers.Core.CL.MessageDelivery;
@@ -23,12 +22,12 @@ namespace Sers.CL.ClrZmq.ThreadWait
 
 
 
-        public Action<IDeliveryConnection, ArraySegment<byte>> Conn_OnGetFrame {  set => _conn.OnGetFrame = value; }
+        public Action<IDeliveryConnection, ArraySegment<byte>> Conn_OnGetFrame { set => _conn.OnGetFrame = value; }
+
+        public Action<IDeliveryConnection> Conn_OnDisconnected { set => _conn.Conn_OnDisconnected = value; }
 
-        public Action<IDeliveryConnection> Conn_OnDisconnected {  set => _conn.Conn_OnDisconnected = value; }
 
 
-        
 
 
         SocketPoller poller = new SocketPoller();
@@ -40,7 +39,7 @@ namespace Sers.CL.ClrZmq.ThreadWait
         public string endpoint = "tcp://127.0.0.1:4502";
 
         public bool Connect()
-        {         
+        {
 
             try
             {
@@ -107,12 +106,12 @@ namespace Sers.CL.ClrZmq.ThreadWait
             _conn.OnGetFrame(_conn, msgFrame.BytesToArraySegmentByte());
         }
 
-        void Zmq_SendMessageAsync(DeliveryConnection conn,byte[] data)
+        void Zmq_SendMessageAsync(DeliveryConnection conn, byte[] data)
         {
-            poller.SendMessageAsync(new ZMessage() { new ZFrame(data) });            
+            poller.SendMessageAsync(new ZMessage() { new ZFrame(data) });
         }
 
-       
+
 
 
         public void Close()
@@ -142,7 +141,7 @@ namespace Sers.CL.ClrZmq.ThreadWait
             {
                 Logger.Error(ex);
             }
- 
+
         }
 
         private void SendCloseSignal()

+ 7 - 8
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/Sers.CL.ClrZmq.ThreadWait/DeliveryConnection.cs

@@ -1,5 +1,4 @@
 using System;
-using System.Collections.Generic;
 
 using Sers.Core.CL.MessageDelivery;
 
@@ -9,7 +8,7 @@ using Vit.Extensions.Json_Extensions;
 namespace Sers.CL.ClrZmq.ThreadWait
 {
     public class DeliveryConnection : IDeliveryConnection
-    {       
+    {
         ~DeliveryConnection()
         {
             Close();
@@ -30,10 +29,10 @@ namespace Sers.CL.ClrZmq.ThreadWait
         Action<IDeliveryConnection, ArraySegment<byte>> _OnGetFrame;
         public Action<IDeliveryConnection, ArraySegment<byte>> OnGetFrame
         {
-            internal get=> _OnGetFrame;
+            internal get => _OnGetFrame;
             set
             {
-              
+
                 if (_securityManager != null)
                 {
                     value =
@@ -51,16 +50,16 @@ namespace Sers.CL.ClrZmq.ThreadWait
             var bytes = data.ToBytes();
 
             _securityManager?.Encryption(bytes.BytesToArraySegmentByte());
-         
+
             OnSendFrameAsync(this, bytes);
         }
-        
+
 
         public Action<IDeliveryConnection> Conn_OnDisconnected { get; set; }
 
         public void Close()
-        {             
-            state = DeliveryConnState.closed;             
+        {
+            state = DeliveryConnState.closed;
             try
             {
                 Conn_OnDisconnected?.Invoke(this);

+ 2 - 2
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/Sers.CL.ClrZmq.ThreadWait/DeliveryServer.cs

@@ -18,7 +18,7 @@ namespace Sers.CL.ClrZmq.ThreadWait
 
         public Action<IDeliveryConnection> Conn_OnDisconnected { private get; set; }
         public Action<IDeliveryConnection> Conn_OnConnected { private get; set; }
- 
+
 
         /// <summary>
         ///  connGuid -> conn
@@ -117,7 +117,7 @@ namespace Sers.CL.ClrZmq.ThreadWait
             if (!connMap.TryGetValue(connGuid, out var conn))
             {
                 //新连接
-                conn=Delivery_OnConnected(connGuid);
+                conn = Delivery_OnConnected(connGuid);
             }
             #endregion
 

+ 1 - 1
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/Sers.CL.ClrZmq.ThreadWait/OrganizeServerBuilder.cs

@@ -27,6 +27,6 @@ namespace Sers.CL.ClrZmq.ThreadWait
 
             organizeList.Add(new OrganizeServer(delivery, config));
         }
- 
+
     }
 }

+ 18 - 18
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/Sers.CL.ClrZmq.ThreadWait/SocketPoller4.cs

@@ -27,7 +27,7 @@ namespace Sers.CL.ClrZmq.ThreadWait
 
         public void Dispose()
         {
-            Close(); 
+            Close();
         }
         public void Close()
         {
@@ -38,7 +38,7 @@ namespace Sers.CL.ClrZmq.ThreadWait
                 try
                 {
                     socket.Close();
-                  
+
                 }
                 catch (Exception ex)
                 {
@@ -73,7 +73,7 @@ namespace Sers.CL.ClrZmq.ThreadWait
                 }
                 signalForSend_pusher = null;
             }
-            
+
 
 
         }
@@ -88,14 +88,14 @@ namespace Sers.CL.ClrZmq.ThreadWait
 
         readonly BlockingCollection<ZMessage> zMessageQueueFromMq = new BlockingCollection<ZMessage>();
 
-        byte[] zfDataForSignal =  new byte[1];
+        byte[] zfDataForSignal = new byte[1];
         public void SendMessageAsync(ZMessage data)
-        {            
+        {
             try
             {
                 zMessageQueueFromMq.Add(data);
-                lock (signalForSend_pusher)                   
-                        signalForSend_pusher.Send(new ZFrame(zfDataForSignal));
+                lock (signalForSend_pusher)
+                    signalForSend_pusher.Send(new ZFrame(zfDataForSignal));
 
                 //using (data)
                 //lock (signalForSend_pusher)                   
@@ -107,7 +107,7 @@ namespace Sers.CL.ClrZmq.ThreadWait
                 Logger.Error(ex);
             }
         }
-    
+
 
         /// <summary>
         /// 初始化并开启后台线程
@@ -118,12 +118,12 @@ namespace Sers.CL.ClrZmq.ThreadWait
             Close();
 
             this.socket = socket;
-        
-      
+
+
             signalForSend_puller = new ZSocket(ZSocketType.PULL);
             signalForSend_pusher = new ZSocket(ZSocketType.PUSH);
 
-            string inprocEndpoint = "inproc://Zmq.ClrZmq.ThreadWait_signalForSend_"+CommonHelp.NewGuid();
+            string inprocEndpoint = "inproc://Zmq.ClrZmq.ThreadWait_signalForSend_" + CommonHelp.NewGuid();
             signalForSend_puller.Bind(inprocEndpoint);
             signalForSend_pusher.Connect(inprocEndpoint);
 
@@ -131,7 +131,7 @@ namespace Sers.CL.ClrZmq.ThreadWait
             taskToReceiveMsg.threadName = "Sers.CL.ClrZmq.ThreadWait-taskToReceiveMsg";
             taskToReceiveMsg.threadCount = 1;
             taskToReceiveMsg.Processor = TaskToReceiveMsg;
-            taskToReceiveMsg.Start();      
+            taskToReceiveMsg.Start();
 
         }
         ZSocket signalForSend_puller;
@@ -142,9 +142,9 @@ namespace Sers.CL.ClrZmq.ThreadWait
 
 
         LongThread taskToReceiveMsg = new LongThread();
-       
+
         void TaskToReceiveMsg()
-        {            
+        {
             ZError error;
             ZMessage msg;
 
@@ -156,11 +156,11 @@ namespace Sers.CL.ClrZmq.ThreadWait
                 {
                     while (socket != null)
                     {
-                        if (sockets.PollIn(items, out var msgs, out error,TimeSpan.FromMilliseconds(1000)))
+                        if (sockets.PollIn(items, out var msgs, out error, TimeSpan.FromMilliseconds(1000)))
                         {
                             if (error != null)
                             {
-                                Logger.Error("zmq.PollIn error", error.ToString());                                
+                                Logger.Error("zmq.PollIn error", error.ToString());
                             }
 
                             if (msgs[0] != null)
@@ -173,7 +173,7 @@ namespace Sers.CL.ClrZmq.ThreadWait
                                 {
                                     using (msg)
                                         socket.Send(msg);
-                                }                                                            
+                                }
                             }
                         }
                     }
@@ -186,7 +186,7 @@ namespace Sers.CL.ClrZmq.ThreadWait
         }
         #endregion
 
- 
+
 
 
 

+ 57 - 59
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Devices/PubSubDevice.cs

@@ -1,68 +1,66 @@
 namespace ZeroMQ.Devices
 {
-	using System;
+    /// <summary>
+    /// Device for a Publisher and Subscribers
+    /// </summary>
+    public class PubSubDevice : ZDevice
+    {
+        /// <summary>
+        /// The frontend <see cref="ZSocketType"/> for a forwarder device.
+        /// </summary>
+        public static readonly ZSocketType FrontendType = ZSocketType.XSUB;
 
-	/// <summary>
-	/// Device for a Publisher and Subscribers
-	/// </summary>
-	public class PubSubDevice : ZDevice
-	{
-		/// <summary>
-		/// The frontend <see cref="ZSocketType"/> for a forwarder device.
-		/// </summary>
-		public static readonly ZSocketType FrontendType = ZSocketType.XSUB;
+        /// <summary>
+        /// The backend <see cref="ZSocketType"/> for a forwarder device.
+        /// </summary>
+        public static readonly ZSocketType BackendType = ZSocketType.XPUB;
 
-		/// <summary>
-		/// The backend <see cref="ZSocketType"/> for a forwarder device.
-		/// </summary>
-		public static readonly ZSocketType BackendType = ZSocketType.XPUB;
-		
-		/// <summary>
-		/// Initializes a new instance of the <see cref="PubSubDevice"/> class.
-		/// </summary>
-		public PubSubDevice() : this(ZContext.Current) { }
-		
-		/// <summary>
-		/// Initializes a new instance of the <see cref="PubSubDevice"/> class.
-		/// </summary>
-		public PubSubDevice(ZContext context)
-			: base(context, FrontendType, BackendType)
-		{
-			BackendSetup.SubscribeAll();
-		}
+        /// <summary>
+        /// Initializes a new instance of the <see cref="PubSubDevice"/> class.
+        /// </summary>
+        public PubSubDevice() : this(ZContext.Current) { }
 
-		/// <summary>
-		/// Initializes a new instance of the <see cref="PubSubDevice"/> class.
-		/// </summary>
-		public PubSubDevice(string frontendBindAddr, string backendBindAddr)
-			: this(ZContext.Current, frontendBindAddr, backendBindAddr)
-		{ }
+        /// <summary>
+        /// Initializes a new instance of the <see cref="PubSubDevice"/> class.
+        /// </summary>
+        public PubSubDevice(ZContext context)
+            : base(context, FrontendType, BackendType)
+        {
+            BackendSetup.SubscribeAll();
+        }
 
-		/// <summary>
-		/// Initializes a new instance of the <see cref="PubSubDevice"/> class.
-		/// </summary>
-		public PubSubDevice(ZContext context, string frontendBindAddr, string backendBindAddr)
-			: base(context, FrontendType, BackendType)
-		{
-			FrontendSetup.Bind(frontendBindAddr);
-			BackendSetup.Bind(backendBindAddr);
-			BackendSetup.SubscribeAll();
-		}
+        /// <summary>
+        /// Initializes a new instance of the <see cref="PubSubDevice"/> class.
+        /// </summary>
+        public PubSubDevice(string frontendBindAddr, string backendBindAddr)
+            : this(ZContext.Current, frontendBindAddr, backendBindAddr)
+        { }
 
-		/// <summary>
-		/// Forwards requests from the frontend socket to the backend socket.
-		/// </summary>
-		protected override bool FrontendHandler(ZSocket socket, out ZMessage message, out ZError error)
-		{
-			return FrontendSocket.Forward(BackendSocket, out message, out error);
-		}
+        /// <summary>
+        /// Initializes a new instance of the <see cref="PubSubDevice"/> class.
+        /// </summary>
+        public PubSubDevice(ZContext context, string frontendBindAddr, string backendBindAddr)
+            : base(context, FrontendType, BackendType)
+        {
+            FrontendSetup.Bind(frontendBindAddr);
+            BackendSetup.Bind(backendBindAddr);
+            BackendSetup.SubscribeAll();
+        }
 
-		/// <summary>
-		/// PubSub Forwards the Subscription messages
-		/// </summary>
-		protected override bool BackendHandler(ZSocket args, out ZMessage message, out ZError error)
-		{
-			return BackendSocket.Forward(FrontendSocket, out message, out error);
-		}
-	}
+        /// <summary>
+        /// Forwards requests from the frontend socket to the backend socket.
+        /// </summary>
+        protected override bool FrontendHandler(ZSocket socket, out ZMessage message, out ZError error)
+        {
+            return FrontendSocket.Forward(BackendSocket, out message, out error);
+        }
+
+        /// <summary>
+        /// PubSub Forwards the Subscription messages
+        /// </summary>
+        protected override bool BackendHandler(ZSocket args, out ZMessage message, out ZError error)
+        {
+            return BackendSocket.Forward(FrontendSocket, out message, out error);
+        }
+    }
 }

+ 54 - 54
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Devices/PushPullDevice.cs

@@ -1,65 +1,65 @@
 namespace ZeroMQ.Devices
 {
-	using System;
+    using System;
 
-	/// <summary>
-	/// Queuing Push-Pull Device
-	/// </summary>
-	public class PushPullDevice : ZDevice
-	{
-		/// <summary>
-		/// The frontend <see cref="ZSocketType"/> for a streamer device.
-		/// </summary>
-		public static readonly ZSocketType FrontendType = ZSocketType.PULL;
+    /// <summary>
+    /// Queuing Push-Pull Device
+    /// </summary>
+    public class PushPullDevice : ZDevice
+    {
+        /// <summary>
+        /// The frontend <see cref="ZSocketType"/> for a streamer device.
+        /// </summary>
+        public static readonly ZSocketType FrontendType = ZSocketType.PULL;
 
-		/// <summary>
-		/// The backend <see cref="ZSocketType"/> for a streamer device.
-		/// </summary>
-		public static readonly ZSocketType BackendType = ZSocketType.PUSH;
+        /// <summary>
+        /// The backend <see cref="ZSocketType"/> for a streamer device.
+        /// </summary>
+        public static readonly ZSocketType BackendType = ZSocketType.PUSH;
 
-		/// <summary>
-		/// Initializes a new instance of the <see cref="PushPullDevice"/> class.
-		/// </summary>
-		public PushPullDevice() : this(ZContext.Current) { }
+        /// <summary>
+        /// Initializes a new instance of the <see cref="PushPullDevice"/> class.
+        /// </summary>
+        public PushPullDevice() : this(ZContext.Current) { }
 
-		/// <summary>
-		/// Initializes a new instance of the <see cref="PushPullDevice"/> class.
-		/// </summary>
-		public PushPullDevice(ZContext context)
-			: base(context, FrontendType, BackendType)
-		{ }
+        /// <summary>
+        /// Initializes a new instance of the <see cref="PushPullDevice"/> class.
+        /// </summary>
+        public PushPullDevice(ZContext context)
+            : base(context, FrontendType, BackendType)
+        { }
 
-		/// <summary>
-		/// Initializes a new instance of the <see cref="PushPullDevice"/> class.
-		/// </summary>
-		public PushPullDevice(string frontendBindAddr, string backendBindAddr)
-			: this(ZContext.Current, frontendBindAddr, backendBindAddr)
-		{ }
+        /// <summary>
+        /// Initializes a new instance of the <see cref="PushPullDevice"/> class.
+        /// </summary>
+        public PushPullDevice(string frontendBindAddr, string backendBindAddr)
+            : this(ZContext.Current, frontendBindAddr, backendBindAddr)
+        { }
 
-		/// <summary>
-		/// Initializes a new instance of the <see cref="PushPullDevice"/> class.
-		/// </summary>
-		public PushPullDevice(ZContext context, string frontendBindAddr, string backendBindAddr)
-			: base(context, FrontendType, BackendType)
-		{
-			FrontendSetup.Bind(frontendBindAddr);
-			BackendSetup.Bind(backendBindAddr);
-		}
+        /// <summary>
+        /// Initializes a new instance of the <see cref="PushPullDevice"/> class.
+        /// </summary>
+        public PushPullDevice(ZContext context, string frontendBindAddr, string backendBindAddr)
+            : base(context, FrontendType, BackendType)
+        {
+            FrontendSetup.Bind(frontendBindAddr);
+            BackendSetup.Bind(backendBindAddr);
+        }
 
-		/// <summary>
-		/// Forwards requests from the frontend socket to the backend socket.
-		/// </summary>
-		protected override bool FrontendHandler(ZSocket args, out ZMessage message, out ZError error)
-		{
-			return FrontendSocket.Forward(BackendSocket, out message, out error);
-		}
+        /// <summary>
+        /// Forwards requests from the frontend socket to the backend socket.
+        /// </summary>
+        protected override bool FrontendHandler(ZSocket args, out ZMessage message, out ZError error)
+        {
+            return FrontendSocket.Forward(BackendSocket, out message, out error);
+        }
 
-		/// <summary>
-		/// Not implemented for the <see cref="PushPullDevice"/>.
-		/// </summary>
-		protected override bool BackendHandler(ZSocket args, out ZMessage message, out ZError error)
-		{
-			throw new NotSupportedException();
-		}
-	}
+        /// <summary>
+        /// Not implemented for the <see cref="PushPullDevice"/>.
+        /// </summary>
+        protected override bool BackendHandler(ZSocket args, out ZMessage message, out ZError error)
+        {
+            throw new NotSupportedException();
+        }
+    }
 }

+ 57 - 57
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Devices/RouterDealerDevice.cs

@@ -1,65 +1,65 @@
 namespace ZeroMQ.Devices
 {
-	/// <summary>
-	/// A Device on Routers and Dealers
-	/// </summary>
-	public class RouterDealerDevice : ZDevice
-	{
-		/// <summary>
-		/// The frontend <see cref="ZSocketType"/> for a queue device.
-		/// </summary>
-		public static readonly ZSocketType FrontendType = ZSocketType.ROUTER;
+    /// <summary>
+    /// A Device on Routers and Dealers
+    /// </summary>
+    public class RouterDealerDevice : ZDevice
+    {
+        /// <summary>
+        /// The frontend <see cref="ZSocketType"/> for a queue device.
+        /// </summary>
+        public static readonly ZSocketType FrontendType = ZSocketType.ROUTER;
 
-		/// <summary>
-		/// The backend <see cref="ZSocketType"/> for a queue device.
-		/// </summary>
-		public static readonly ZSocketType BackendType = ZSocketType.DEALER;
-		
-		/// <summary>
-		/// Initializes a new instance of the <see cref="RouterDealerDevice"/> class.
-		/// </summary>
-		public RouterDealerDevice() : this(ZContext.Current) { }
+        /// <summary>
+        /// The backend <see cref="ZSocketType"/> for a queue device.
+        /// </summary>
+        public static readonly ZSocketType BackendType = ZSocketType.DEALER;
 
-		/// <summary>
-		/// Initializes a new instance of the <see cref="RouterDealerDevice"/> class.
-		/// </summary>
-		public RouterDealerDevice(ZContext context)
-			: base(context, FrontendType, BackendType)
-		{ }
-		
-		/// <summary>
-		/// Initializes a new instance of the <see cref="RouterDealerDevice"/> class
-		/// and binds to the specified Frontend and Backend address.
-		/// </summary>
-		public RouterDealerDevice(string frontendBindAddr, string backendBindAddr)
-			: this(ZContext.Current, frontendBindAddr, backendBindAddr)
-		{ }
+        /// <summary>
+        /// Initializes a new instance of the <see cref="RouterDealerDevice"/> class.
+        /// </summary>
+        public RouterDealerDevice() : this(ZContext.Current) { }
 
-		/// <summary>
-		/// Initializes a new instance of the <see cref="RouterDealerDevice"/> class
-		/// and binds to the specified Frontend and Backend address.
-		/// </summary>
-		public RouterDealerDevice(ZContext context, string frontendBindAddr, string backendBindAddr)
-			: base(context, FrontendType, BackendType)
-		{
-			FrontendSetup.Bind(frontendBindAddr);
-			BackendSetup.Bind(backendBindAddr);
-		}
+        /// <summary>
+        /// Initializes a new instance of the <see cref="RouterDealerDevice"/> class.
+        /// </summary>
+        public RouterDealerDevice(ZContext context)
+            : base(context, FrontendType, BackendType)
+        { }
 
-		/// <summary>
-		/// Forwards requests from the frontend socket to the backend socket.
-		/// </summary>
-		protected override bool FrontendHandler(ZSocket args, out ZMessage message, out ZError error)
-		{
-			return FrontendSocket.Forward(BackendSocket, out message, out error);
-		}
+        /// <summary>
+        /// Initializes a new instance of the <see cref="RouterDealerDevice"/> class
+        /// and binds to the specified Frontend and Backend address.
+        /// </summary>
+        public RouterDealerDevice(string frontendBindAddr, string backendBindAddr)
+            : this(ZContext.Current, frontendBindAddr, backendBindAddr)
+        { }
 
-		/// <summary>
-		/// Forwards replies from the backend socket to the frontend socket.
-		/// </summary>
-		protected override bool BackendHandler(ZSocket args, out ZMessage message, out ZError error)
-		{
-			return BackendSocket.Forward(FrontendSocket, out message, out error);
-		}
-	}
+        /// <summary>
+        /// Initializes a new instance of the <see cref="RouterDealerDevice"/> class
+        /// and binds to the specified Frontend and Backend address.
+        /// </summary>
+        public RouterDealerDevice(ZContext context, string frontendBindAddr, string backendBindAddr)
+            : base(context, FrontendType, BackendType)
+        {
+            FrontendSetup.Bind(frontendBindAddr);
+            BackendSetup.Bind(backendBindAddr);
+        }
+
+        /// <summary>
+        /// Forwards requests from the frontend socket to the backend socket.
+        /// </summary>
+        protected override bool FrontendHandler(ZSocket args, out ZMessage message, out ZError error)
+        {
+            return FrontendSocket.Forward(BackendSocket, out message, out error);
+        }
+
+        /// <summary>
+        /// Forwards replies from the backend socket to the frontend socket.
+        /// </summary>
+        protected override bool BackendHandler(ZSocket args, out ZMessage message, out ZError error)
+        {
+            return BackendSocket.Forward(FrontendSocket, out message, out error);
+        }
+    }
 }

+ 208 - 211
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Devices/StreamDealerDevice.cs

@@ -1,209 +1,206 @@
 namespace ZeroMQ.Devices
 {
-	using lib;
-	// using lib.sys;
-
-	using System;
-	using System.Net;
-	using System.Threading;
-
-	/// <summary>
-	/// The Stream to Dealer is a Device for reading 
-	/// and sending REPlies to TCP
-	/// </summary>
-	public class StreamDealerDevice : ZDevice
-	{
-		/// <summary>
-		/// The frontend <see cref="ZSocketType"/> for a queue device.
-		/// </summary>
-		public static readonly ZSocketType FrontendType = ZSocketType.STREAM;
-
-		/// <summary>
-		/// The backend <see cref="ZSocketType"/> for a queue device.
-		/// </summary>
-		public static readonly ZSocketType BackendType = ZSocketType.DEALER;
-		
-		/// <summary>
-		/// Initializes a new instance of the <see cref="StreamDealerDevice"/> class.
-		/// </summary>
-		public StreamDealerDevice() : this(ZContext.Current) { }
-		/// <summary>
-		/// Initializes a new instance of the <see cref="StreamDealerDevice"/> class.
-		/// </summary>
-		public StreamDealerDevice(ZContext context)
-			: base(context, FrontendType, BackendType)
-		{ }
-		
-		/// <summary>
-		/// Initializes a new instance of the <see cref="StreamDealerDevice"/> class.
-		/// </summary>
-		public StreamDealerDevice(string frontendBindAddr, string backendBindAddr)
-			: this(ZContext.Current, frontendBindAddr, backendBindAddr)
-		{ }
-
-		/// <summary>
-		/// Initializes a new instance of the <see cref="StreamDealerDevice"/> class.
-		/// </summary>
-		public StreamDealerDevice(ZContext context, string frontendBindAddr, string backendBindAddr)
-			: base(context, FrontendType, BackendType)
-		{
-			FrontendSetup.Bind(frontendBindAddr);
-			BackendSetup.Bind(backendBindAddr);
-		}
-
-		/// <summary>
-		/// Forwards requests from the frontend socket to the backend socket.
-		/// </summary>
-		protected override bool FrontendHandler(ZSocket sock, out ZMessage message, out ZError error)
-		{
-			error = default(ZError);
-			message = null;
-
-			// receiving scope
-			// STREAM: get 2 frames, identity and body
-			ZMessage incoming = null;
-			// IPAddress address = null;
-			string address;
-			if (!ReceiveMsg(sock, ref incoming, out address, out error))
-			{
-				return false;
-			}
-
-			// sending scope
-			// DEALER: forward
-			using (incoming)
-			{
-				if (incoming[1].Length == 0)
-				{
-					return true; // Ignore the Empty one
-				}
-
-				// Prepend empty delimiter between Identity frame and Data frame
-				incoming.Insert(1, new ZFrame());
-
-				// Prepend Peer-Address
-				incoming.Insert(2, new ZFrame(address));
-
-				if (!BackendSocket.Send(incoming, /* ZSocketFlags.DontWait, */ out error))
-				{
-					return false;
-				}
-				incoming.Dismiss();
-			}
-
-			return true;
-		}
-
-		static bool ReceiveMsg(ZSocket sock, ref ZMessage message, out string address, out ZError error)
-		{
-			error = ZError.None;
-			// address = IPAddress.None;
-			address = string.Empty;
-
-			// STREAM: read frames: identity, body
-
-			// read the ip4 address from (ZFrame)frame.GetOption("Peer-Address")
-
-			int receiveCount = 2;
-			do
-			{
-				var frame = ZFrame.CreateEmpty();
-
-				while (-1 == zmq.msg_recv(frame.Ptr, sock.SocketPtr, (int)(/* ZSocketFlags.DontWait | */ ZSocketFlags.More)))
-				{
-					error = ZError.GetLastErr();
-
-					if (error == ZError.EINTR) 
-					{
-						error = default(ZError);
-						continue;
-					}
-
-					frame.Dispose();
-					return false;
-				}
-
-				if (message == null)
-				{
-					message = new ZMessage();
-				}
-				message.Add(frame);
-
-				if (receiveCount == 2)
-				{
-					if (default(string) == (address = frame.GetOption("Peer-Address", out error)))
-					{
-						// just ignore
-						error = default(ZError);
-						address = string.Empty;
-					}
-				}
-
-			} while (--receiveCount > 0);
-
-			return true;
-		}
-
-
-		/// <summary>
-		/// Forwards replies from the backend socket to the frontend socket.
-		/// </summary>
-		protected override bool BackendHandler(ZSocket sock, out ZMessage message, out ZError error)
-		{
-			error = default(ZError);
-			message = null;
-
-			// receiving scope
-			// DEALER: normal movemsg
-			ZMessage incoming = null;
-			if (!sock.ReceiveMessage(ref incoming, /* ZSocketFlags.DontWait */ ZSocketFlags.None, out error))
-			{
-				return false;
-			}
-
-			using (incoming)
-			{
-				// STREAM: write frames: identity, body, identity, empty
-				// Read identity
-				int ic = (int)incoming[0].Length;
-				var identityBytes = new byte[ic];
-				incoming[0].Read(identityBytes, 0, ic); 
-
-				// Remove DEALER's delimiter
-				incoming.RemoveAt(1);
-
-				// Append Identity frame
-				var identity0 = new ZFrame(identityBytes);
-				incoming.Add(identity0);
-
-				// Append STREAM's empty delimiter frame
-				incoming.Add(new ZFrame());
-
-				if (!SendMsg(FrontendSocket, incoming, out error))
-				{
-					return false;
-				}
-			}
-
-			return true;
-		}
-
-		static bool SendMsg(ZSocket sock, ZMessage msg, out ZError error)
-		{
-			error = ZError.None;
-
-			foreach (ZFrame frame in msg)
-			{
-				while (-1 == zmq.msg_send(frame.Ptr, sock.SocketPtr, (int)(/* ZSocketFlags.DontWait | */ ZSocketFlags.More)))
-				{
-					error = ZError.GetLastErr();
-
-					if (error == ZError.EINTR)
-					{
-						error = default(ZError);
-						continue;
-					}
-					/* if (error == ZError.EAGAIN)
+    using lib;
+    // using lib.sys;
+
+
+    /// <summary>
+    /// The Stream to Dealer is a Device for reading 
+    /// and sending REPlies to TCP
+    /// </summary>
+    public class StreamDealerDevice : ZDevice
+    {
+        /// <summary>
+        /// The frontend <see cref="ZSocketType"/> for a queue device.
+        /// </summary>
+        public static readonly ZSocketType FrontendType = ZSocketType.STREAM;
+
+        /// <summary>
+        /// The backend <see cref="ZSocketType"/> for a queue device.
+        /// </summary>
+        public static readonly ZSocketType BackendType = ZSocketType.DEALER;
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="StreamDealerDevice"/> class.
+        /// </summary>
+        public StreamDealerDevice() : this(ZContext.Current) { }
+        /// <summary>
+        /// Initializes a new instance of the <see cref="StreamDealerDevice"/> class.
+        /// </summary>
+        public StreamDealerDevice(ZContext context)
+            : base(context, FrontendType, BackendType)
+        { }
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="StreamDealerDevice"/> class.
+        /// </summary>
+        public StreamDealerDevice(string frontendBindAddr, string backendBindAddr)
+            : this(ZContext.Current, frontendBindAddr, backendBindAddr)
+        { }
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="StreamDealerDevice"/> class.
+        /// </summary>
+        public StreamDealerDevice(ZContext context, string frontendBindAddr, string backendBindAddr)
+            : base(context, FrontendType, BackendType)
+        {
+            FrontendSetup.Bind(frontendBindAddr);
+            BackendSetup.Bind(backendBindAddr);
+        }
+
+        /// <summary>
+        /// Forwards requests from the frontend socket to the backend socket.
+        /// </summary>
+        protected override bool FrontendHandler(ZSocket sock, out ZMessage message, out ZError error)
+        {
+            error = default(ZError);
+            message = null;
+
+            // receiving scope
+            // STREAM: get 2 frames, identity and body
+            ZMessage incoming = null;
+            // IPAddress address = null;
+            string address;
+            if (!ReceiveMsg(sock, ref incoming, out address, out error))
+            {
+                return false;
+            }
+
+            // sending scope
+            // DEALER: forward
+            using (incoming)
+            {
+                if (incoming[1].Length == 0)
+                {
+                    return true; // Ignore the Empty one
+                }
+
+                // Prepend empty delimiter between Identity frame and Data frame
+                incoming.Insert(1, new ZFrame());
+
+                // Prepend Peer-Address
+                incoming.Insert(2, new ZFrame(address));
+
+                if (!BackendSocket.Send(incoming, /* ZSocketFlags.DontWait, */ out error))
+                {
+                    return false;
+                }
+                incoming.Dismiss();
+            }
+
+            return true;
+        }
+
+        static bool ReceiveMsg(ZSocket sock, ref ZMessage message, out string address, out ZError error)
+        {
+            error = ZError.None;
+            // address = IPAddress.None;
+            address = string.Empty;
+
+            // STREAM: read frames: identity, body
+
+            // read the ip4 address from (ZFrame)frame.GetOption("Peer-Address")
+
+            int receiveCount = 2;
+            do
+            {
+                var frame = ZFrame.CreateEmpty();
+
+                while (-1 == zmq.msg_recv(frame.Ptr, sock.SocketPtr, (int)(/* ZSocketFlags.DontWait | */ ZSocketFlags.More)))
+                {
+                    error = ZError.GetLastErr();
+
+                    if (error == ZError.EINTR)
+                    {
+                        error = default(ZError);
+                        continue;
+                    }
+
+                    frame.Dispose();
+                    return false;
+                }
+
+                if (message == null)
+                {
+                    message = new ZMessage();
+                }
+                message.Add(frame);
+
+                if (receiveCount == 2)
+                {
+                    if (default(string) == (address = frame.GetOption("Peer-Address", out error)))
+                    {
+                        // just ignore
+                        error = default(ZError);
+                        address = string.Empty;
+                    }
+                }
+
+            } while (--receiveCount > 0);
+
+            return true;
+        }
+
+
+        /// <summary>
+        /// Forwards replies from the backend socket to the frontend socket.
+        /// </summary>
+        protected override bool BackendHandler(ZSocket sock, out ZMessage message, out ZError error)
+        {
+            error = default(ZError);
+            message = null;
+
+            // receiving scope
+            // DEALER: normal movemsg
+            ZMessage incoming = null;
+            if (!sock.ReceiveMessage(ref incoming, /* ZSocketFlags.DontWait */ ZSocketFlags.None, out error))
+            {
+                return false;
+            }
+
+            using (incoming)
+            {
+                // STREAM: write frames: identity, body, identity, empty
+                // Read identity
+                int ic = (int)incoming[0].Length;
+                var identityBytes = new byte[ic];
+                incoming[0].Read(identityBytes, 0, ic);
+
+                // Remove DEALER's delimiter
+                incoming.RemoveAt(1);
+
+                // Append Identity frame
+                var identity0 = new ZFrame(identityBytes);
+                incoming.Add(identity0);
+
+                // Append STREAM's empty delimiter frame
+                incoming.Add(new ZFrame());
+
+                if (!SendMsg(FrontendSocket, incoming, out error))
+                {
+                    return false;
+                }
+            }
+
+            return true;
+        }
+
+        static bool SendMsg(ZSocket sock, ZMessage msg, out ZError error)
+        {
+            error = ZError.None;
+
+            foreach (ZFrame frame in msg)
+            {
+                while (-1 == zmq.msg_send(frame.Ptr, sock.SocketPtr, (int)(/* ZSocketFlags.DontWait | */ ZSocketFlags.More)))
+                {
+                    error = ZError.GetLastErr();
+
+                    if (error == ZError.EINTR)
+                    {
+                        error = default(ZError);
+                        continue;
+                    }
+                    /* if (error == ZError.EAGAIN)
 					{
 						error = default(ZError);
 						Thread.Sleep(1);
@@ -211,12 +208,12 @@
 						continue;
 					} */
 
-					return false;
-				}
-			}
+                    return false;
+                }
+            }
 
-			msg.Dismiss();
-			return true;
-		}
-	}
+            msg.Dismiss();
+            return true;
+        }
+    }
 }

+ 259 - 263
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Monitoring/ZMonitor.cs

@@ -1,278 +1,274 @@
 using System;
 using System.Collections.Generic;
 using System.Diagnostics;
-using System.Linq;
-using System.Runtime.InteropServices;
 using System.Threading;
 
-using ZeroMQ.lib;
-
 namespace ZeroMQ.Monitoring
 {
 
-	/// <summary>
-	/// Monitors state change events on another socket within the same context.
-	/// </summary>
-	public class ZMonitor : ZThread
-	{
-		/// <summary>
-		/// The polling interval in milliseconds.
-		/// </summary>
-		public static readonly TimeSpan PollingInterval = TimeSpan.FromMilliseconds(64);
+    /// <summary>
+    /// Monitors state change events on another socket within the same context.
+    /// </summary>
+    public class ZMonitor : ZThread
+    {
+        /// <summary>
+        /// The polling interval in milliseconds.
+        /// </summary>
+        public static readonly TimeSpan PollingInterval = TimeSpan.FromMilliseconds(64);
 
-		private ZSocket _socket;
+        private ZSocket _socket;
 
-		private readonly string _endpoint;
+        private readonly string _endpoint;
 
-		private readonly Dictionary<ZMonitorEvents, Action<ZMonitorEventData>> _eventHandler;
+        private readonly Dictionary<ZMonitorEvents, Action<ZMonitorEventData>> _eventHandler;
 
-		protected ZMonitor(ZSocket socket, string endpoint)
-			: this(ZContext.Current, socket, endpoint) 
-		{ }
+        protected ZMonitor(ZSocket socket, string endpoint)
+            : this(ZContext.Current, socket, endpoint)
+        { }
 
-		protected ZMonitor(ZContext context, ZSocket socket, string endpoint)
-			: base()
-		{
+        protected ZMonitor(ZContext context, ZSocket socket, string endpoint)
+            : base()
+        {
             // TODO: remove socket argument and create socket within Run?
-			_socket = socket;
-			_endpoint = endpoint;
-			_eventHandler = new Dictionary<ZMonitorEvents, Action<ZMonitorEventData>>
-			{
-				{ ZMonitorEvents.AllEvents, data => InvokeEvent(AllEvents, () => new ZMonitorEventArgs(this, data)) },
-				{ ZMonitorEvents.Connected, data => InvokeEvent(Connected, () => new ZMonitorFileDescriptorEventArgs(this, data)) },
-				{ ZMonitorEvents.ConnectDelayed, data => InvokeEvent(ConnectDelayed, () => new ZMonitorEventArgs(this, data)) },
-				{ ZMonitorEvents.ConnectRetried, data => InvokeEvent(ConnectRetried, () => new ZMonitorIntervalEventArgs(this, data)) },
-				{ ZMonitorEvents.Listening, data => InvokeEvent(Listening, () => new ZMonitorFileDescriptorEventArgs(this, data)) },
-				{ ZMonitorEvents.BindFailed, data => InvokeEvent(BindFailed, () => new ZMonitorEventArgs(this, data)) },
-				{ ZMonitorEvents.Accepted, data => InvokeEvent(Accepted, () => new ZMonitorFileDescriptorEventArgs(this, data)) },
-				{ ZMonitorEvents.AcceptFailed, data => InvokeEvent(AcceptFailed, () => new ZMonitorEventArgs(this, data)) },
-				{ ZMonitorEvents.Closed, data => InvokeEvent(Closed, () => new ZMonitorFileDescriptorEventArgs(this, data)) },
-				{ ZMonitorEvents.CloseFailed, data => InvokeEvent(CloseFailed, () => new ZMonitorEventArgs(this, data)) },
-				{ ZMonitorEvents.Disconnected, data => InvokeEvent(Disconnected, () => new ZMonitorFileDescriptorEventArgs(this, data)) },
-				{ ZMonitorEvents.Stopped, data => InvokeEvent(Stopped, () => new ZMonitorEventArgs(this, data)) },
-			};
-		}
-
-		public static ZMonitor Create(string endpoint)
-		{
-			return Create(ZContext.Current, endpoint);
-		}
-
-		public static ZMonitor Create(ZContext context, string endpoint)
-		{
-			ZError error;
-			ZMonitor monitor;
-			if (null == (monitor = ZMonitor.Create(context, endpoint, out error)))
-			{
-				throw new ZException(error);
-			}
-			return monitor;
-		}
-
-		/// <summary>
-		/// Create a socket with the current context and the specified socket type.
-		/// </summary>
-		/// <param name="socketType">A <see cref="ZSocketType"/> value for the socket.</param>
-		/// <returns>A <see cref="ZSocket"/> instance with the current context and the specified socket type.</returns>
-		public static ZMonitor Create(string endpoint, out ZError error)
-		{
-			return Create(ZContext.Current, endpoint, out error);
-		}
-
-		/// <summary>
-		/// Create a socket with the current context and the specified socket type.
-		/// </summary>
-		/// <param name="socketType">A <see cref="ZSocketType"/> value for the socket.</param>
-		/// <returns>A <see cref="ZSocket"/> instance with the current context and the specified socket type.</returns>
-		public static ZMonitor Create(ZContext context, string endpoint, out ZError error)
-		{
-			ZSocket socket;
-			if (null == (socket = ZSocket.Create(context, ZSocketType.PAIR, out error)))
-			{
-				return default(ZMonitor);
-			}
-
-			return new ZMonitor(context, socket, endpoint);
-		}
-
-		public event EventHandler<ZMonitorEventArgs> AllEvents;
-
-		/// <summary>
-		/// Occurs when a new connection is established.
-		/// NOTE: Do not rely on the <see cref="ZMonitorEventArgs.Address"/> value for
-		/// 'Connected' messages, as the memory address contained in the message may no longer
-		/// point to the correct value.
-		/// </summary>
-		public event EventHandler<ZMonitorFileDescriptorEventArgs> Connected;
-
-		/// <summary>
-		/// Occurs when a synchronous connection attempt failed, and its completion is being polled for.
-		/// </summary>
-		public event EventHandler<ZMonitorEventArgs> ConnectDelayed;
-
-		/// <summary>
-		/// Occurs when an asynchronous connect / reconnection attempt is being handled by a reconnect timer.
-		/// </summary>
-		public event EventHandler<ZMonitorIntervalEventArgs> ConnectRetried;
-
-		/// <summary>
-		/// Occurs when a socket is bound to an address and is ready to accept connections.
-		/// </summary>
-		public event EventHandler<ZMonitorFileDescriptorEventArgs> Listening;
-
-		/// <summary>
-		/// Occurs when a socket could not bind to an address.
-		/// </summary>
-		public event EventHandler<ZMonitorEventArgs> BindFailed;
-
-		/// <summary>
-		/// Occurs when a connection from a remote peer has been established with a socket's listen address.
-		/// </summary>
-		public event EventHandler<ZMonitorFileDescriptorEventArgs> Accepted;
-
-		/// <summary>
-		/// Occurs when a connection attempt to a socket's bound address fails.
-		/// </summary>
-		public event EventHandler<ZMonitorEventArgs> AcceptFailed;
-
-		/// <summary>
-		/// Occurs when a connection was closed.
-		/// NOTE: Do not rely on the <see cref="ZMonitorEventArgs.Address"/> value for
-		/// 'Closed' messages, as the memory address contained in the message may no longer
-		/// point to the correct value.
-		/// </summary>
-		public event EventHandler<ZMonitorFileDescriptorEventArgs> Closed;
-
-		/// <summary>
-		/// Occurs when a connection couldn't be closed.
-		/// </summary>
-		public event EventHandler<ZMonitorEventArgs> CloseFailed;
-
-		/// <summary>
-		/// Occurs when the stream engine (tcp and ipc specific) detects a corrupted / broken session.
-		/// </summary>
-		public event EventHandler<ZMonitorFileDescriptorEventArgs> Disconnected;
-
-		/// <summary>
-		/// Monitoring on this socket ended.
-		/// </summary>
-		public event EventHandler<ZMonitorEventArgs> Stopped;
-
-		/// <summary>
-		/// Gets the endpoint to which the monitor socket is connected.
-		/// </summary>
-		public string Endpoint
-		{
-			get { return _endpoint; }
-		}
-
-		// private static readonly int sizeof_MonitorEventData = Marshal.SizeOf(typeof(ZMonitorEventData));
-
-	    /// <summary>
-	    /// Begins monitoring for state changes, raising the appropriate events as they arrive.
-	    /// </summary>
-	    /// <remarks>NOTE: This is a blocking method and should be run from another thread.</remarks>
-	    protected override void Run()
-	    {
-	        using (_socket)
-	        {
-	            ZError error;
-	            if (!_socket.Connect(_endpoint, out error))
-	            {
-	                LogError(error, "connect");
-	                return;
-	            }
-
-	            var poller = ZPollItem.CreateReceiver();
-
-	            while (!Cancellor.IsCancellationRequested)
-	            {
-	                ZMessage incoming;
-	                if (!_socket.PollIn(poller, out incoming, out error, PollingInterval))
-	                {
-	                    if (error == ZError.EAGAIN)
-	                    {
-	                        // TODO: why sleep here? the loop frequency is already controlled by PollingInterval
-	                        Thread.Sleep(1);
-	                        continue;
-	                    }
-
-	                    LogError(error, "poll");
-	                }
-
-	                var eventValue = new ZMonitorEventData();
-
-	                using (incoming)
-	                {
-	                    if (incoming.Count > 0)
-	                    {
-	                        eventValue.Event = (ZMonitorEvents)incoming[0].ReadInt16();
-	                        eventValue.EventValue = incoming[0].ReadInt32();
-	                    }
-
-	                    if (incoming.Count > 1)
-	                    {
-	                        eventValue.Address = incoming[1].ReadString();
-	                    }
-	                }
-
-	                OnMonitor(eventValue);
-	            }
-
-	            if (!_socket.Disconnect(_endpoint, out error))
-	            {
-	                LogError(error, "disconnect");
-	            }
-	        }
-	    }
-
-	    private void LogError(ZError error, string context)
-	    {
-	        // TODO: this error handling is somewhat too subtle; the client should be able to retrieve it
-	        if (error != ZError.ETERM)
-	        {
-	            Trace.TraceError("error on {0}: {1}", context, error.ToString());
-	        }
-	    }
-
-	    internal void OnMonitor(ZMonitorEventData data)
-		{
-			if (_eventHandler.ContainsKey(ZMonitorEvents.AllEvents))
-			{
-				_eventHandler[ZMonitorEvents.AllEvents](data);
-			}
-			if (_eventHandler.ContainsKey(data.Event))
-			{
-				_eventHandler[data.Event](data);
-			}
-		}
-
-		/// <summary>
-		/// Releases the unmanaged resources used by the <see cref="ZMonitor"/>, and optionally disposes of the managed resources.
-		/// </summary>
-		/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
-		protected override void Dispose(bool disposing)
-		{
-			if (!_disposed)
-			{
-				if (disposing)
-				{
-					if (_socket != null)
-					{
-						_socket.Dispose();
-						_socket = null;
-					}
-				}
-			}
-			base.Dispose(disposing);
-		}
-
-		private void InvokeEvent<T>(EventHandler<T> handler, Func<T> createEventArgs) where T : EventArgs
-		{
-			if (handler != null)
-			{
-				handler(this, createEventArgs());
-			}
-		}
-	}
+            _socket = socket;
+            _endpoint = endpoint;
+            _eventHandler = new Dictionary<ZMonitorEvents, Action<ZMonitorEventData>>
+            {
+                { ZMonitorEvents.AllEvents, data => InvokeEvent(AllEvents, () => new ZMonitorEventArgs(this, data)) },
+                { ZMonitorEvents.Connected, data => InvokeEvent(Connected, () => new ZMonitorFileDescriptorEventArgs(this, data)) },
+                { ZMonitorEvents.ConnectDelayed, data => InvokeEvent(ConnectDelayed, () => new ZMonitorEventArgs(this, data)) },
+                { ZMonitorEvents.ConnectRetried, data => InvokeEvent(ConnectRetried, () => new ZMonitorIntervalEventArgs(this, data)) },
+                { ZMonitorEvents.Listening, data => InvokeEvent(Listening, () => new ZMonitorFileDescriptorEventArgs(this, data)) },
+                { ZMonitorEvents.BindFailed, data => InvokeEvent(BindFailed, () => new ZMonitorEventArgs(this, data)) },
+                { ZMonitorEvents.Accepted, data => InvokeEvent(Accepted, () => new ZMonitorFileDescriptorEventArgs(this, data)) },
+                { ZMonitorEvents.AcceptFailed, data => InvokeEvent(AcceptFailed, () => new ZMonitorEventArgs(this, data)) },
+                { ZMonitorEvents.Closed, data => InvokeEvent(Closed, () => new ZMonitorFileDescriptorEventArgs(this, data)) },
+                { ZMonitorEvents.CloseFailed, data => InvokeEvent(CloseFailed, () => new ZMonitorEventArgs(this, data)) },
+                { ZMonitorEvents.Disconnected, data => InvokeEvent(Disconnected, () => new ZMonitorFileDescriptorEventArgs(this, data)) },
+                { ZMonitorEvents.Stopped, data => InvokeEvent(Stopped, () => new ZMonitorEventArgs(this, data)) },
+            };
+        }
+
+        public static ZMonitor Create(string endpoint)
+        {
+            return Create(ZContext.Current, endpoint);
+        }
+
+        public static ZMonitor Create(ZContext context, string endpoint)
+        {
+            ZError error;
+            ZMonitor monitor;
+            if (null == (monitor = ZMonitor.Create(context, endpoint, out error)))
+            {
+                throw new ZException(error);
+            }
+            return monitor;
+        }
+
+        /// <summary>
+        /// Create a socket with the current context and the specified socket type.
+        /// </summary>
+        /// <param name="socketType">A <see cref="ZSocketType"/> value for the socket.</param>
+        /// <returns>A <see cref="ZSocket"/> instance with the current context and the specified socket type.</returns>
+        public static ZMonitor Create(string endpoint, out ZError error)
+        {
+            return Create(ZContext.Current, endpoint, out error);
+        }
+
+        /// <summary>
+        /// Create a socket with the current context and the specified socket type.
+        /// </summary>
+        /// <param name="socketType">A <see cref="ZSocketType"/> value for the socket.</param>
+        /// <returns>A <see cref="ZSocket"/> instance with the current context and the specified socket type.</returns>
+        public static ZMonitor Create(ZContext context, string endpoint, out ZError error)
+        {
+            ZSocket socket;
+            if (null == (socket = ZSocket.Create(context, ZSocketType.PAIR, out error)))
+            {
+                return default(ZMonitor);
+            }
+
+            return new ZMonitor(context, socket, endpoint);
+        }
+
+        public event EventHandler<ZMonitorEventArgs> AllEvents;
+
+        /// <summary>
+        /// Occurs when a new connection is established.
+        /// NOTE: Do not rely on the <see cref="ZMonitorEventArgs.Address"/> value for
+        /// 'Connected' messages, as the memory address contained in the message may no longer
+        /// point to the correct value.
+        /// </summary>
+        public event EventHandler<ZMonitorFileDescriptorEventArgs> Connected;
+
+        /// <summary>
+        /// Occurs when a synchronous connection attempt failed, and its completion is being polled for.
+        /// </summary>
+        public event EventHandler<ZMonitorEventArgs> ConnectDelayed;
+
+        /// <summary>
+        /// Occurs when an asynchronous connect / reconnection attempt is being handled by a reconnect timer.
+        /// </summary>
+        public event EventHandler<ZMonitorIntervalEventArgs> ConnectRetried;
+
+        /// <summary>
+        /// Occurs when a socket is bound to an address and is ready to accept connections.
+        /// </summary>
+        public event EventHandler<ZMonitorFileDescriptorEventArgs> Listening;
+
+        /// <summary>
+        /// Occurs when a socket could not bind to an address.
+        /// </summary>
+        public event EventHandler<ZMonitorEventArgs> BindFailed;
+
+        /// <summary>
+        /// Occurs when a connection from a remote peer has been established with a socket's listen address.
+        /// </summary>
+        public event EventHandler<ZMonitorFileDescriptorEventArgs> Accepted;
+
+        /// <summary>
+        /// Occurs when a connection attempt to a socket's bound address fails.
+        /// </summary>
+        public event EventHandler<ZMonitorEventArgs> AcceptFailed;
+
+        /// <summary>
+        /// Occurs when a connection was closed.
+        /// NOTE: Do not rely on the <see cref="ZMonitorEventArgs.Address"/> value for
+        /// 'Closed' messages, as the memory address contained in the message may no longer
+        /// point to the correct value.
+        /// </summary>
+        public event EventHandler<ZMonitorFileDescriptorEventArgs> Closed;
+
+        /// <summary>
+        /// Occurs when a connection couldn't be closed.
+        /// </summary>
+        public event EventHandler<ZMonitorEventArgs> CloseFailed;
+
+        /// <summary>
+        /// Occurs when the stream engine (tcp and ipc specific) detects a corrupted / broken session.
+        /// </summary>
+        public event EventHandler<ZMonitorFileDescriptorEventArgs> Disconnected;
+
+        /// <summary>
+        /// Monitoring on this socket ended.
+        /// </summary>
+        public event EventHandler<ZMonitorEventArgs> Stopped;
+
+        /// <summary>
+        /// Gets the endpoint to which the monitor socket is connected.
+        /// </summary>
+        public string Endpoint
+        {
+            get { return _endpoint; }
+        }
+
+        // private static readonly int sizeof_MonitorEventData = Marshal.SizeOf(typeof(ZMonitorEventData));
+
+        /// <summary>
+        /// Begins monitoring for state changes, raising the appropriate events as they arrive.
+        /// </summary>
+        /// <remarks>NOTE: This is a blocking method and should be run from another thread.</remarks>
+        protected override void Run()
+        {
+            using (_socket)
+            {
+                ZError error;
+                if (!_socket.Connect(_endpoint, out error))
+                {
+                    LogError(error, "connect");
+                    return;
+                }
+
+                var poller = ZPollItem.CreateReceiver();
+
+                while (!Cancellor.IsCancellationRequested)
+                {
+                    ZMessage incoming;
+                    if (!_socket.PollIn(poller, out incoming, out error, PollingInterval))
+                    {
+                        if (error == ZError.EAGAIN)
+                        {
+                            // TODO: why sleep here? the loop frequency is already controlled by PollingInterval
+                            Thread.Sleep(1);
+                            continue;
+                        }
+
+                        LogError(error, "poll");
+                    }
+
+                    var eventValue = new ZMonitorEventData();
+
+                    using (incoming)
+                    {
+                        if (incoming.Count > 0)
+                        {
+                            eventValue.Event = (ZMonitorEvents)incoming[0].ReadInt16();
+                            eventValue.EventValue = incoming[0].ReadInt32();
+                        }
+
+                        if (incoming.Count > 1)
+                        {
+                            eventValue.Address = incoming[1].ReadString();
+                        }
+                    }
+
+                    OnMonitor(eventValue);
+                }
+
+                if (!_socket.Disconnect(_endpoint, out error))
+                {
+                    LogError(error, "disconnect");
+                }
+            }
+        }
+
+        private void LogError(ZError error, string context)
+        {
+            // TODO: this error handling is somewhat too subtle; the client should be able to retrieve it
+            if (error != ZError.ETERM)
+            {
+                Trace.TraceError("error on {0}: {1}", context, error.ToString());
+            }
+        }
+
+        internal void OnMonitor(ZMonitorEventData data)
+        {
+            if (_eventHandler.ContainsKey(ZMonitorEvents.AllEvents))
+            {
+                _eventHandler[ZMonitorEvents.AllEvents](data);
+            }
+            if (_eventHandler.ContainsKey(data.Event))
+            {
+                _eventHandler[data.Event](data);
+            }
+        }
+
+        /// <summary>
+        /// Releases the unmanaged resources used by the <see cref="ZMonitor"/>, and optionally disposes of the managed resources.
+        /// </summary>
+        /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
+        protected override void Dispose(bool disposing)
+        {
+            if (!_disposed)
+            {
+                if (disposing)
+                {
+                    if (_socket != null)
+                    {
+                        _socket.Dispose();
+                        _socket = null;
+                    }
+                }
+            }
+            base.Dispose(disposing);
+        }
+
+        private void InvokeEvent<T>(EventHandler<T> handler, Func<T> createEventArgs) where T : EventArgs
+        {
+            if (handler != null)
+            {
+                handler(this, createEventArgs());
+            }
+        }
+    }
 }

+ 22 - 22
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Monitoring/ZMonitorEventArgs.cs

@@ -1,28 +1,28 @@
 namespace ZeroMQ.Monitoring
 {
-	using System;
+    using System;
 
-	/// <summary>
-	/// A base class for the all ZmqMonitor events.
-	/// </summary>
-	public class ZMonitorEventArgs : EventArgs
-	{
-		/// <summary>
-		/// Initializes a new instance of the <see cref="ZMonitorEventArgs"/> class.
-		/// </summary>
-		/// <param name="monitor">The <see cref="ZMonitor"/> that triggered the event.</param>
-		/// <param name="address">The peer address.</param>
-		public ZMonitorEventArgs(ZMonitor monitor, ZMonitorEventData ed)
-		{
-			this.Monitor = monitor;
-			this.Event = ed;
-		}
+    /// <summary>
+    /// A base class for the all ZmqMonitor events.
+    /// </summary>
+    public class ZMonitorEventArgs : EventArgs
+    {
+        /// <summary>
+        /// Initializes a new instance of the <see cref="ZMonitorEventArgs"/> class.
+        /// </summary>
+        /// <param name="monitor">The <see cref="ZMonitor"/> that triggered the event.</param>
+        /// <param name="address">The peer address.</param>
+        public ZMonitorEventArgs(ZMonitor monitor, ZMonitorEventData ed)
+        {
+            this.Monitor = monitor;
+            this.Event = ed;
+        }
 
-		public ZMonitorEventData Event { get; private set; }
+        public ZMonitorEventData Event { get; private set; }
 
-		/// <summary>
-		/// Gets the monitor that triggered the event.
-		/// </summary>
-		public ZMonitor Monitor { get; private set; }
-	}
+        /// <summary>
+        /// Gets the monitor that triggered the event.
+        /// </summary>
+        public ZMonitor Monitor { get; private set; }
+    }
 }

+ 7 - 7
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Monitoring/ZMonitorEventData.cs

@@ -1,11 +1,11 @@
 namespace ZeroMQ.Monitoring
 {
-	using System;
+    using System;
 
-	public struct ZMonitorEventData
-	{
-		public ZMonitorEvents Event;
-		public Int32 EventValue;
-		public String Address;
-	}
+    public struct ZMonitorEventData
+    {
+        public ZMonitorEvents Event;
+        public Int32 EventValue;
+        public String Address;
+    }
 }

+ 56 - 56
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Monitoring/ZMonitorEvents.cs

@@ -1,71 +1,71 @@
 namespace ZeroMQ.Monitoring
 {
-	using System;
+    using System;
 
-	/// <summary>
-	/// Socket transport events (for TCP and IPC sockets) that can be monitored.
-	/// </summary>
-	[Flags]
-	public enum ZMonitorEvents
-	{
-		/// <summary>
-		/// Triggered when a connection has been established to a remote peer.
-		/// </summary>
-		Connected = 1,
+    /// <summary>
+    /// Socket transport events (for TCP and IPC sockets) that can be monitored.
+    /// </summary>
+    [Flags]
+    public enum ZMonitorEvents
+    {
+        /// <summary>
+        /// Triggered when a connection has been established to a remote peer.
+        /// </summary>
+        Connected = 1,
 
-		/// <summary>
-		/// Triggered when an immediate connection attempt is delayed and it's completion is being polled for.
-		/// </summary>
-		ConnectDelayed = 2,
+        /// <summary>
+        /// Triggered when an immediate connection attempt is delayed and it's completion is being polled for.
+        /// </summary>
+        ConnectDelayed = 2,
 
-		/// <summary>
-		/// Triggered when a connection attempt is being handled by reconnect timer. The reconnect interval is recomputed for each attempt.
-		/// </summary>
-		ConnectRetried = 4,
+        /// <summary>
+        /// Triggered when a connection attempt is being handled by reconnect timer. The reconnect interval is recomputed for each attempt.
+        /// </summary>
+        ConnectRetried = 4,
 
-		/// <summary>
-		/// Triggered when a socket is successfully bound to a an interface.
-		/// </summary>
-		Listening = 8,
+        /// <summary>
+        /// Triggered when a socket is successfully bound to a an interface.
+        /// </summary>
+        Listening = 8,
 
-		/// <summary>
-		/// Triggered when a socket could not bind to a given interface.
-		/// </summary>
-		BindFailed = 16,
+        /// <summary>
+        /// Triggered when a socket could not bind to a given interface.
+        /// </summary>
+        BindFailed = 16,
 
-		/// <summary>
-		/// Triggered when a connection from a remote peer has been established with a socket's listen address.
-		/// </summary>
-		Accepted = 32,
+        /// <summary>
+        /// Triggered when a connection from a remote peer has been established with a socket's listen address.
+        /// </summary>
+        Accepted = 32,
 
-		/// <summary>
-		/// Triggered when a connection attempt to a socket's bound address fails.
-		/// </summary>
-		AcceptFailed = 64,
+        /// <summary>
+        /// Triggered when a connection attempt to a socket's bound address fails.
+        /// </summary>
+        AcceptFailed = 64,
 
-		/// <summary>
-		/// Triggered when a connection's underlying descriptor has been closed.
-		/// </summary>
-		Closed = 128,
+        /// <summary>
+        /// Triggered when a connection's underlying descriptor has been closed.
+        /// </summary>
+        Closed = 128,
 
-		/// <summary>
-		/// Triggered when a descriptor could not be released back to the OS.
-		/// </summary>
-		CloseFailed = 256,
+        /// <summary>
+        /// Triggered when a descriptor could not be released back to the OS.
+        /// </summary>
+        CloseFailed = 256,
 
-		/// <summary>
-		/// Triggered when the stream engine (tcp and ipc specific) detects a corrupted / broken session.
-		/// </summary>
-		Disconnected = 512,
+        /// <summary>
+        /// Triggered when the stream engine (tcp and ipc specific) detects a corrupted / broken session.
+        /// </summary>
+        Disconnected = 512,
 
-		/// <summary>
-		/// Monitoring on this socket ended.
-		/// </summary>
-		Stopped = 1024,
+        /// <summary>
+        /// Monitoring on this socket ended.
+        /// </summary>
+        Stopped = 1024,
 
-		/// <summary>
-		/// Any <see cref="ZMonitorEvents"/> event, maybe readable from EventValue.
-		/// </summary>
-		AllEvents = 0xFFFF
-	}
+        /// <summary>
+        /// Any <see cref="ZMonitorEvents"/> event, maybe readable from EventValue.
+        /// </summary>
+        AllEvents = 0xFFFF
+    }
 }

+ 33 - 32
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Monitoring/ZMonitorFileDescriptorEventArgs.cs

@@ -1,38 +1,39 @@
 namespace ZeroMQ.Monitoring
 {
-	using System;
-	using lib;
+    using System;
 
-	/// <summary>
-	/// Provides data for <see cref="ZMonitor.Connected"/>, <see cref="ZMonitor.Listening"/>, <see cref="ZMonitor.Accepted"/>, <see cref="ZMonitor.Closed"/> and <see cref="ZMonitor.Disconnected"/> events.
-	/// </summary>
-	public class ZMonitorFileDescriptorEventArgs : ZMonitorEventArgs
-	{
-		internal ZMonitorFileDescriptorEventArgs(ZMonitor monitor, ZMonitorEventData data)
-			: base(monitor, data)
-		{
-			if (Platform.Kind == PlatformKind.Posix)
-			{
-				this.FileDescriptor_Posix = data.EventValue;
-			}
-			else if (Platform.Kind == PlatformKind.Win32)
-			{
-				this.FileDescriptor_Windows = new IntPtr(data.EventValue);
-			}
-			else
-			{
-				throw new PlatformNotSupportedException();
-			}
-		}
+    using lib;
 
-		/// <summary>
-		/// Gets the monitor descriptor (Posix)
-		/// </summary>
-		public int FileDescriptor_Posix { get; private set; }
+    /// <summary>
+    /// Provides data for <see cref="ZMonitor.Connected"/>, <see cref="ZMonitor.Listening"/>, <see cref="ZMonitor.Accepted"/>, <see cref="ZMonitor.Closed"/> and <see cref="ZMonitor.Disconnected"/> events.
+    /// </summary>
+    public class ZMonitorFileDescriptorEventArgs : ZMonitorEventArgs
+    {
+        internal ZMonitorFileDescriptorEventArgs(ZMonitor monitor, ZMonitorEventData data)
+            : base(monitor, data)
+        {
+            if (Platform.Kind == PlatformKind.Posix)
+            {
+                this.FileDescriptor_Posix = data.EventValue;
+            }
+            else if (Platform.Kind == PlatformKind.Win32)
+            {
+                this.FileDescriptor_Windows = new IntPtr(data.EventValue);
+            }
+            else
+            {
+                throw new PlatformNotSupportedException();
+            }
+        }
 
-		/// <summary>
-		/// Gets the monitor descriptor (Windows)
-		/// </summary>
-		public IntPtr FileDescriptor_Windows { get; private set; }
-	}
+        /// <summary>
+        /// Gets the monitor descriptor (Posix)
+        /// </summary>
+        public int FileDescriptor_Posix { get; private set; }
+
+        /// <summary>
+        /// Gets the monitor descriptor (Windows)
+        /// </summary>
+        public IntPtr FileDescriptor_Windows { get; private set; }
+    }
 }

+ 15 - 15
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Monitoring/ZMonitorIntervalEventArgs.cs

@@ -1,19 +1,19 @@
 namespace ZeroMQ.Monitoring
 {
-	/// <summary>
-	/// Provides data for <see cref="ZMonitor.ConnectRetried"/> event.
-	/// </summary>
-	public class ZMonitorIntervalEventArgs : ZMonitorEventArgs
-	{
-		internal ZMonitorIntervalEventArgs(ZMonitor monitor, ZMonitorEventData data)
-			: base(monitor, data)
-		{
-			this.Interval = data.EventValue;
-		}
+    /// <summary>
+    /// Provides data for <see cref="ZMonitor.ConnectRetried"/> event.
+    /// </summary>
+    public class ZMonitorIntervalEventArgs : ZMonitorEventArgs
+    {
+        internal ZMonitorIntervalEventArgs(ZMonitor monitor, ZMonitorEventData data)
+            : base(monitor, data)
+        {
+            this.Interval = data.EventValue;
+        }
 
-		/// <summary>
-		/// Gets the computed reconnect interval.
-		/// </summary>
-		public int Interval { get; private set; }
-	}
+        /// <summary>
+        /// Gets the computed reconnect interval.
+        /// </summary>
+        public int Interval { get; private set; }
+    }
 }

+ 74 - 75
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Monitoring/ZMonitors.cs

@@ -1,92 +1,91 @@
 using System;
-using System.Runtime.InteropServices;
 
 using ZeroMQ.lib;
 
 namespace ZeroMQ.Monitoring
 {
 
-	/// <summary>
-	/// Defines extension methods related to monitoring for <see cref="ZSocket"/> instances.
-	/// </summary>
-	public static class ZMonitors
-	{
-		/// <summary>
-		/// Spawns a <see cref="ZSocketType.PAIR"/> socket that publishes all events for
-		/// the specified socket over the inproc transport at the given endpoint.
-		/// </summary>
-		public static bool Monitor(this ZSocket socket, string endpoint)
-		{
-			ZError error;
-			if (!Monitor(socket, endpoint, ZMonitorEvents.AllEvents, out error))
-			{
-				throw new ZException(error);
-			}
-			return true;
-		}
+    /// <summary>
+    /// Defines extension methods related to monitoring for <see cref="ZSocket"/> instances.
+    /// </summary>
+    public static class ZMonitors
+    {
+        /// <summary>
+        /// Spawns a <see cref="ZSocketType.PAIR"/> socket that publishes all events for
+        /// the specified socket over the inproc transport at the given endpoint.
+        /// </summary>
+        public static bool Monitor(this ZSocket socket, string endpoint)
+        {
+            ZError error;
+            if (!Monitor(socket, endpoint, ZMonitorEvents.AllEvents, out error))
+            {
+                throw new ZException(error);
+            }
+            return true;
+        }
 
-		/// <summary>
-		/// Spawns a <see cref="ZSocketType.PAIR"/> socket that publishes all events for
-		/// the specified socket over the inproc transport at the given endpoint.
-		/// </summary>
-		public static bool Monitor(this ZSocket socket, string endpoint, out ZError error)
-		{
-			return Monitor(socket, endpoint, ZMonitorEvents.AllEvents, out error);
-		}
+        /// <summary>
+        /// Spawns a <see cref="ZSocketType.PAIR"/> socket that publishes all events for
+        /// the specified socket over the inproc transport at the given endpoint.
+        /// </summary>
+        public static bool Monitor(this ZSocket socket, string endpoint, out ZError error)
+        {
+            return Monitor(socket, endpoint, ZMonitorEvents.AllEvents, out error);
+        }
 
-		/// <summary>
-		/// Spawns a <see cref="ZSocketType.PAIR"/> socket that publishes all events for
-		/// the specified socket over the inproc transport at the given endpoint.
-		/// </summary>
-		public static bool Monitor(this ZSocket socket, string endpoint, ZMonitorEvents eventsToMonitor)
-		{
-			ZError error;
-			if (!Monitor(socket, endpoint, eventsToMonitor, out error))
-			{
-				throw new ZException(error);
-			}
-			return true;
-		}
+        /// <summary>
+        /// Spawns a <see cref="ZSocketType.PAIR"/> socket that publishes all events for
+        /// the specified socket over the inproc transport at the given endpoint.
+        /// </summary>
+        public static bool Monitor(this ZSocket socket, string endpoint, ZMonitorEvents eventsToMonitor)
+        {
+            ZError error;
+            if (!Monitor(socket, endpoint, eventsToMonitor, out error))
+            {
+                throw new ZException(error);
+            }
+            return true;
+        }
 
-		/// <summary>
-		/// Spawns a <see cref="ZSocketType.PAIR"/> socket that publishes all events for
-		/// the specified socket over the inproc transport at the given endpoint.
-		/// </summary>
-		public static bool Monitor(this ZSocket socket, string endpoint, ZMonitorEvents eventsToMonitor, out ZError error)
-		{
-			if (socket == null)
-			{
-				throw new ArgumentNullException("socket");
-			}
+        /// <summary>
+        /// Spawns a <see cref="ZSocketType.PAIR"/> socket that publishes all events for
+        /// the specified socket over the inproc transport at the given endpoint.
+        /// </summary>
+        public static bool Monitor(this ZSocket socket, string endpoint, ZMonitorEvents eventsToMonitor, out ZError error)
+        {
+            if (socket == null)
+            {
+                throw new ArgumentNullException("socket");
+            }
 
-			if (endpoint == null)
-			{
-				throw new ArgumentNullException("endpoint");
-			}
+            if (endpoint == null)
+            {
+                throw new ArgumentNullException("endpoint");
+            }
 
-			if (endpoint == string.Empty)
-			{
-				throw new ArgumentException("Unable to publish socket events to an empty endpoint.", "endpoint");
-			}
+            if (endpoint == string.Empty)
+            {
+                throw new ArgumentException("Unable to publish socket events to an empty endpoint.", "endpoint");
+            }
 
-			error = ZError.None;
+            error = ZError.None;
 
-			using (var endpointPtr = DispoIntPtr.AllocString(endpoint))
-			{
-				while (-1 == zmq.socket_monitor(socket.SocketPtr, endpointPtr, (Int32)eventsToMonitor))
-				{
-					error = ZError.GetLastErr();
+            using (var endpointPtr = DispoIntPtr.AllocString(endpoint))
+            {
+                while (-1 == zmq.socket_monitor(socket.SocketPtr, endpointPtr, (Int32)eventsToMonitor))
+                {
+                    error = ZError.GetLastErr();
 
-					if (error == ZError.EINTR)
-					{
-						error = default(ZError);
-						continue;
-					}
+                    if (error == ZError.EINTR)
+                    {
+                        error = default(ZError);
+                        continue;
+                    }
 
-					return false;
-				}
-			}
-			return true;
-		}
-	}
+                    return false;
+                }
+            }
+            return true;
+        }
+    }
 }

+ 23 - 26
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/DispoIntPtr.Ansi.cs

@@ -1,27 +1,24 @@
-using System.Threading;
-
-namespace ZeroMQ.lib
+namespace ZeroMQ.lib
 {
-	using System;
-	using System.Text;
-	using System.Threading;
-	using System.Runtime.InteropServices;
-
-	internal sealed partial class DispoIntPtr : IDisposable
-	{
-		public static class Ansi
-		{
-			unsafe internal static DispoIntPtr AllocStringNative(string str, out int byteCount)
-			{
-				// use builtin allocation
-				var dispPtr = new DispoIntPtr();
-				dispPtr._ptr = Marshal.StringToHGlobalAnsi(str);
-				dispPtr.isAllocated = true;
-
-				byteCount = Encoding.Default.GetByteCount(str);
-				return dispPtr;  /**/
-
-				/* use encoding or Encoding.Default ( system codepage of ANSI )
+    using System;
+    using System.Runtime.InteropServices;
+    using System.Text;
+
+    internal sealed partial class DispoIntPtr : IDisposable
+    {
+        public static class Ansi
+        {
+            unsafe internal static DispoIntPtr AllocStringNative(string str, out int byteCount)
+            {
+                // use builtin allocation
+                var dispPtr = new DispoIntPtr();
+                dispPtr._ptr = Marshal.StringToHGlobalAnsi(str);
+                dispPtr.isAllocated = true;
+
+                byteCount = Encoding.Default.GetByteCount(str);
+                return dispPtr;  /**/
+
+                /* use encoding or Encoding.Default ( system codepage of ANSI )
 				var enc = Encoding.Default.GetEncoder();
 
 				// var encoded = new byte[length];
@@ -50,7 +47,7 @@ namespace ZeroMQ.lib
 				// *((byte*)dispPtr._ptr + length) = 0x00;
 
 				return dispPtr; /**/
-			}
-		}
-	}
+            }
+        }
+    }
 }

+ 120 - 124
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/DispoIntPtr.cs

@@ -1,135 +1,131 @@
-using System.Threading;
-
-namespace ZeroMQ.lib
+namespace ZeroMQ.lib
 {
-	using System;
-	using System.Text;
-	using System.Threading;
-	using System.Runtime.InteropServices;
+    using System;
+    using System.Runtime.InteropServices;
 
     internal sealed partial class DispoIntPtr : IDisposable
-	{
-		private delegate DispoIntPtr AllocStringNativeDelegate(string str, out int byteCount);
+    {
+        private delegate DispoIntPtr AllocStringNativeDelegate(string str, out int byteCount);
 
-		private static readonly AllocStringNativeDelegate AllocStringNative = Ansi.AllocStringNative;
+        private static readonly AllocStringNativeDelegate AllocStringNative = Ansi.AllocStringNative;
 
-		/* static DispoIntPtr() {
+        /* static DispoIntPtr() {
 			// Platform.SetupPlatformImplementation(typeof(DispoIntPtr));
 		} */
 
-		public static DispoIntPtr Alloc(int size)
-		{
-			var dispPtr = new DispoIntPtr();
-			dispPtr._ptr = Marshal.AllocHGlobal(size);
-			dispPtr.isAllocated = true;
-			return dispPtr;
-		}
-
-		public static DispoIntPtr AllocString(string str)
-		{
-			int byteCount;
-			return AllocString(str, out byteCount);
-		}
-
-		public static DispoIntPtr AllocString(string str, out int byteCount)
-		{
-			return AllocStringNative(str, out byteCount);
-		}
-
-		public static implicit operator IntPtr(DispoIntPtr dispoIntPtr)
-		{
-			return dispoIntPtr == null ? IntPtr.Zero : dispoIntPtr._ptr;
-		}
-
-		unsafe public static explicit operator void*(DispoIntPtr dispoIntPtr)
-		{
-			return dispoIntPtr == null ? (void*)null : (void*)dispoIntPtr._ptr;
-		}
-
-		unsafe public static explicit operator byte*(DispoIntPtr dispoIntPtr)
-		{
-			return dispoIntPtr == null ? (byte*)null : (byte*)dispoIntPtr._ptr;
-		}
-
-		unsafe public static explicit operator sbyte*(DispoIntPtr dispoIntPtr)
-		{
-			return dispoIntPtr == null ? (sbyte*)null : (sbyte*)dispoIntPtr._ptr;
-		}
-
-		unsafe public static explicit operator short*(DispoIntPtr dispoIntPtr)
-		{
-			return dispoIntPtr == null ? (short*)null : (short*)dispoIntPtr._ptr;
-		}
-
-		unsafe public static explicit operator ushort*(DispoIntPtr dispoIntPtr)
-		{
-			return dispoIntPtr == null ? (ushort*)null : (ushort*)dispoIntPtr._ptr;
-		}
-
-		unsafe public static explicit operator char*(DispoIntPtr dispoIntPtr)
-		{
-			return dispoIntPtr == null ? (char*)null : (char*)dispoIntPtr._ptr;
-		}
-
-		unsafe public static explicit operator int*(DispoIntPtr dispoIntPtr)
-		{
-			return dispoIntPtr == null ? (int*)null : (int*)dispoIntPtr._ptr;
-		}
-
-		unsafe public static explicit operator uint*(DispoIntPtr dispoIntPtr)
-		{
-			return dispoIntPtr == null ? (uint*)null : (uint*)dispoIntPtr._ptr;
-		}
-
-		unsafe public static explicit operator long*(DispoIntPtr dispoIntPtr)
-		{
-			return dispoIntPtr == null ? (long*)null : (long*)dispoIntPtr._ptr;
-		}
-
-		unsafe public static explicit operator ulong*(DispoIntPtr dispoIntPtr)
-		{
-			return dispoIntPtr == null ? (ulong*)null : (ulong*)dispoIntPtr._ptr;
-		}
-
-		private bool isAllocated;
-
-		private IntPtr _ptr;
-
-		public IntPtr Ptr
-		{
-			get { return _ptr; }
-		}
-
-		internal DispoIntPtr() { }
-
-		~DispoIntPtr()
-		{
-			Dispose(false);
-		}
-
-		public void Dispose()
-		{
-			Dispose(true);
-			GC.SuppressFinalize(this);
-		}
-
-		void Dispose(bool disposing)
-		{
-			// TODO: instance ThreadStatic && do ( o == null ? return : ( lock(o, ms), check threadId, .. ) ) 
-			IntPtr handle = _ptr;
-			if (handle != IntPtr.Zero)
-			{
-				if (isAllocated)
-				{
-					Marshal.FreeHGlobal(handle);
-					isAllocated = false;
-				}
-				_ptr = IntPtr.Zero;
-			}
-		}
-
-		/* public void ReAlloc(long size) {
+        public static DispoIntPtr Alloc(int size)
+        {
+            var dispPtr = new DispoIntPtr();
+            dispPtr._ptr = Marshal.AllocHGlobal(size);
+            dispPtr.isAllocated = true;
+            return dispPtr;
+        }
+
+        public static DispoIntPtr AllocString(string str)
+        {
+            int byteCount;
+            return AllocString(str, out byteCount);
+        }
+
+        public static DispoIntPtr AllocString(string str, out int byteCount)
+        {
+            return AllocStringNative(str, out byteCount);
+        }
+
+        public static implicit operator IntPtr(DispoIntPtr dispoIntPtr)
+        {
+            return dispoIntPtr == null ? IntPtr.Zero : dispoIntPtr._ptr;
+        }
+
+        unsafe public static explicit operator void*(DispoIntPtr dispoIntPtr)
+        {
+            return dispoIntPtr == null ? (void*)null : (void*)dispoIntPtr._ptr;
+        }
+
+        unsafe public static explicit operator byte*(DispoIntPtr dispoIntPtr)
+        {
+            return dispoIntPtr == null ? (byte*)null : (byte*)dispoIntPtr._ptr;
+        }
+
+        unsafe public static explicit operator sbyte*(DispoIntPtr dispoIntPtr)
+        {
+            return dispoIntPtr == null ? (sbyte*)null : (sbyte*)dispoIntPtr._ptr;
+        }
+
+        unsafe public static explicit operator short*(DispoIntPtr dispoIntPtr)
+        {
+            return dispoIntPtr == null ? (short*)null : (short*)dispoIntPtr._ptr;
+        }
+
+        unsafe public static explicit operator ushort*(DispoIntPtr dispoIntPtr)
+        {
+            return dispoIntPtr == null ? (ushort*)null : (ushort*)dispoIntPtr._ptr;
+        }
+
+        unsafe public static explicit operator char*(DispoIntPtr dispoIntPtr)
+        {
+            return dispoIntPtr == null ? (char*)null : (char*)dispoIntPtr._ptr;
+        }
+
+        unsafe public static explicit operator int*(DispoIntPtr dispoIntPtr)
+        {
+            return dispoIntPtr == null ? (int*)null : (int*)dispoIntPtr._ptr;
+        }
+
+        unsafe public static explicit operator uint*(DispoIntPtr dispoIntPtr)
+        {
+            return dispoIntPtr == null ? (uint*)null : (uint*)dispoIntPtr._ptr;
+        }
+
+        unsafe public static explicit operator long*(DispoIntPtr dispoIntPtr)
+        {
+            return dispoIntPtr == null ? (long*)null : (long*)dispoIntPtr._ptr;
+        }
+
+        unsafe public static explicit operator ulong*(DispoIntPtr dispoIntPtr)
+        {
+            return dispoIntPtr == null ? (ulong*)null : (ulong*)dispoIntPtr._ptr;
+        }
+
+        private bool isAllocated;
+
+        private IntPtr _ptr;
+
+        public IntPtr Ptr
+        {
+            get { return _ptr; }
+        }
+
+        internal DispoIntPtr() { }
+
+        ~DispoIntPtr()
+        {
+            Dispose(false);
+        }
+
+        public void Dispose()
+        {
+            Dispose(true);
+            GC.SuppressFinalize(this);
+        }
+
+        void Dispose(bool disposing)
+        {
+            // TODO: instance ThreadStatic && do ( o == null ? return : ( lock(o, ms), check threadId, .. ) ) 
+            IntPtr handle = _ptr;
+            if (handle != IntPtr.Zero)
+            {
+                if (isAllocated)
+                {
+                    Marshal.FreeHGlobal(handle);
+                    isAllocated = false;
+                }
+                _ptr = IntPtr.Zero;
+            }
+        }
+
+        /* public void ReAlloc(long size) {
 			_ptr = Marshal.ReAllocHGlobal(_ptr, new IntPtr(size));
 		} */
-	}
+    }
 }

+ 10 - 10
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/Platform.MacOSX.cs

@@ -1,14 +1,14 @@
 namespace ZeroMQ.lib
 {
 
-	public static partial class Platform
-	{
-		public static class MacOSX
-		{
+    public static partial class Platform
+    {
+        public static class MacOSX
+        {
 
-			// public const string LibraryFileExtension = ".dylib";
+            // public const string LibraryFileExtension = ".dylib";
 
-			public static readonly string[] LibraryPaths = new string[] {
+            public static readonly string[] LibraryPaths = new string[] {
                 "/lib/{LibraryName}*.dylib",
                 "/lib/{LibraryName}*.dylib.*",
                 "/usr/lib/{LibraryName}*.dylib",
@@ -19,10 +19,10 @@
                 "{DllPath}/{LibraryName}*.dylib.*",
                 "{Path}/{LibraryName}*.dylib",
                 "{Path}/{LibraryName}*.dylib.*",
-				"{AppBase}/{Arch}/{LibraryName}*.dylib",
-				"{AppBase}/{Arch}/{LibraryName}*.dylib.*",
+                "{AppBase}/{Arch}/{LibraryName}*.dylib",
+                "{AppBase}/{Arch}/{LibraryName}*.dylib.*",
             };
 
-		}
-	}
+        }
+    }
 }

+ 249 - 248
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/Platform.Posix.cs

@@ -1,66 +1,65 @@
 namespace ZeroMQ.lib
 {
-	using System;
-	using System.Collections.Generic;
-	using System.Configuration;
-	using System.Diagnostics;
-	using System.IO;
-	using System.Linq;
-	using System.Reflection;
-	using System.Runtime.InteropServices;
-	using System.Text;
+    using System;
+    using System.Collections.Generic;
+    using System.Diagnostics;
+    using System.IO;
+    using System.Linq;
+    using System.Reflection;
+    using System.Runtime.InteropServices;
+    using System.Text;
 
-	public static partial class Platform
-	{
-		public static class Posix
-		{
-			private const CallingConvention CCCdecl = CallingConvention.Cdecl;
+    public static partial class Platform
+    {
+        public static class Posix
+        {
+            private const CallingConvention CCCdecl = CallingConvention.Cdecl;
 
-			private const string __Internal = "__Internal";
+            private const string __Internal = "__Internal";
 
-			private const string LibraryName = "libdl";
+            private const string LibraryName = "libdl";
 
-			// public const string LibraryFileExtension = ".so";
+            // public const string LibraryFileExtension = ".so";
 
-			public static readonly string[] LibraryPaths = new string[] {
+            public static readonly string[] LibraryPaths = new string[] {
                 "/lib/{LibraryName}*.so",
                 "/lib/{LibraryName}*.so.*",
                 "/usr/lib/{LibraryName}*.so",
                 "/usr/lib/{LibraryName}*.so.*",
                 "/usr/local/lib/{LibraryName}*.so",
                 "/usr/local/lib/{LibraryName}*.so.*",
-				"{DllPath}/{LibraryName}*.so",
-				"{DllPath}/{LibraryName}*.so.*",
+                "{DllPath}/{LibraryName}*.so",
+                "{DllPath}/{LibraryName}*.so.*",
                 "{Path}/{LibraryName}*.so",
                 "{Path}/{LibraryName}*.so.*",
-				"{AppBase}/{Arch}/{LibraryName}*.so",
-				"{AppBase}/{Arch}/{LibraryName}*.so.*",
-			};
+                "{AppBase}/{Arch}/{LibraryName}*.so",
+                "{AppBase}/{Arch}/{LibraryName}*.so.*",
+            };
 
-			private const int RTLD_LAZY = 0x0001;
-			private const int RTLD_NOW = 0x0002;
-			private const int RTLD_GLOBAL = 0x0100;
-			private const int RTLD_LOCAL = 0x0000;
+            private const int RTLD_LAZY = 0x0001;
+            private const int RTLD_NOW = 0x0002;
+            private const int RTLD_GLOBAL = 0x0100;
+            private const int RTLD_LOCAL = 0x0000;
 
-			[DllImport(__Internal, CallingConvention = CCCdecl)]
-			private static extern SafeLibraryHandle dlopen(IntPtr filename, int flags);
+            [DllImport(__Internal, CallingConvention = CCCdecl)]
+            private static extern SafeLibraryHandle dlopen(IntPtr filename, int flags);
 
-			[DllImport(__Internal, CallingConvention = CCCdecl)]
-			private static extern int dlclose(IntPtr handle);
+            [DllImport(__Internal, CallingConvention = CCCdecl)]
+            private static extern int dlclose(IntPtr handle);
 
-			[DllImport(__Internal, CallingConvention = CCCdecl)]
-			private static extern IntPtr dlerror();
+            [DllImport(__Internal, CallingConvention = CCCdecl)]
+            private static extern IntPtr dlerror();
 
-			[DllImport(__Internal, CallingConvention = CCCdecl)]
-			private static extern IntPtr dlsym(SafeLibraryHandle handle, IntPtr symbol);
-			
-			[DllImport(__Internal)]
-			private static extern void mono_dllmap_insert(IntPtr assembly, IntPtr dll, IntPtr func, IntPtr tdll, IntPtr tfunc);
+            [DllImport(__Internal, CallingConvention = CCCdecl)]
+            private static extern IntPtr dlsym(SafeLibraryHandle handle, IntPtr symbol);
 
-			/* [DllImport("libc", EntryPoint = "chmod", SetLastError = true)]
+            [DllImport(__Internal)]
+            private static extern void mono_dllmap_insert(IntPtr assembly, IntPtr dll, IntPtr func, IntPtr tdll, IntPtr tfunc);
+
+            /* [DllImport("libc", EntryPoint = "chmod", SetLastError = true)]
 			internal static extern int syscall_chmod (IntPtr path, uint mode); */
 
-			/* private static void syscall_chmod_execute(string libraryPath) 
+            /* private static void syscall_chmod_execute(string libraryPath) 
 			{
 				IntPtr pathPtr = Marshal.StringToHGlobalAnsi(libraryPath);
 				if (0 != syscall_chmod(pathPtr, (uint)( FilePermissions.ALLPERMS ))) {
@@ -69,215 +68,217 @@
 				Marshal.FreeHGlobal(pathPtr);
 			} */
 
-			private static void MonoDllMapInsert(string libraryName, string libraryPath)
-			{
-				IntPtr libraryNamePtr = Marshal.StringToHGlobalAnsi(libraryName);
-				IntPtr pathPtr = Marshal.StringToHGlobalAnsi(libraryPath);
-				mono_dllmap_insert(IntPtr.Zero, libraryNamePtr, IntPtr.Zero, pathPtr, IntPtr.Zero);
-				Marshal.FreeHGlobal(libraryNamePtr);
-				Marshal.FreeHGlobal(pathPtr);
-			}
+            private static void MonoDllMapInsert(string libraryName, string libraryPath)
+            {
+                IntPtr libraryNamePtr = Marshal.StringToHGlobalAnsi(libraryName);
+                IntPtr pathPtr = Marshal.StringToHGlobalAnsi(libraryPath);
+                mono_dllmap_insert(IntPtr.Zero, libraryNamePtr, IntPtr.Zero, pathPtr, IntPtr.Zero);
+                Marshal.FreeHGlobal(libraryNamePtr);
+                Marshal.FreeHGlobal(pathPtr);
+            }
 
-			public static UnmanagedLibrary LoadUnmanagedLibrary(string libraryName)
-			{
-				if (string.IsNullOrWhiteSpace(libraryName))
-				{
-					throw new ArgumentException("A valid library name is expected.", "libraryName");
-				}
+            public static UnmanagedLibrary LoadUnmanagedLibrary(string libraryName)
+            {
+                if (string.IsNullOrWhiteSpace(libraryName))
+                {
+                    throw new ArgumentException("A valid library name is expected.", "libraryName");
+                }
 
-				// Now look: This method should ExpandPaths on LibraryPaths.
-				// That being said, it should just enumerate
-				// Path, AppBase, Arch, Compiler, LibraryName, Extension
+                // Now look: This method should ExpandPaths on LibraryPaths.
+                // That being said, it should just enumerate
+                // Path, AppBase, Arch, Compiler, LibraryName, Extension
 
-				// Secondly, this method should try each /lib/x86_64-linux-gnu/libload.so.2 to load,
-				// Third, this method should try EmbeddedResources,
-				// Finally, this method fails, telling the user all libraryPaths searched.
+                // Secondly, this method should try each /lib/x86_64-linux-gnu/libload.so.2 to load,
+                // Third, this method should try EmbeddedResources,
+                // Finally, this method fails, telling the user all libraryPaths searched.
 
-				var libraryPaths = new List<string>(Platform.LibraryPaths);
+                var libraryPaths = new List<string>(Platform.LibraryPaths);
 
-				Platform.ExpandPaths(libraryPaths, "{Path}", EnumerateLibLdConf("/etc/ld.so.conf"));
+                Platform.ExpandPaths(libraryPaths, "{Path}", EnumerateLibLdConf("/etc/ld.so.conf"));
 
-				var PATHs = new List<string>();
-				PATHs.Add(EnsureNotEndingSlash(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)));
-				PATHs.AddRange(EnumerateLibLdPATH());
-				Platform.ExpandPaths(libraryPaths, "{DllPath}", PATHs);
+                var PATHs = new List<string>();
+                PATHs.Add(EnsureNotEndingSlash(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)));
+                PATHs.AddRange(EnumerateLibLdPATH());
+                Platform.ExpandPaths(libraryPaths, "{DllPath}", PATHs);
 
-				Platform.ExpandPaths(libraryPaths, "{AppBase}", EnsureNotEndingSlash(
-						AppDomain.CurrentDomain.BaseDirectory));
+                Platform.ExpandPaths(libraryPaths, "{AppBase}", EnsureNotEndingSlash(
+                        AppDomain.CurrentDomain.BaseDirectory));
 
-				Platform.ExpandPaths(libraryPaths, "{LibraryName}", libraryName);
+                Platform.ExpandPaths(libraryPaths, "{LibraryName}", libraryName);
 
-				// Platform.ExpandPaths(libraryPaths, "{Ext}", Platform.LibraryFileExtension);
+                // Platform.ExpandPaths(libraryPaths, "{Ext}", Platform.LibraryFileExtension);
 
-				string architecture;
-				string[] architecturePaths = null;
-				if (Platform.Architecture == ImageFileMachine.I386 && Environment.Is64BitProcess) 
-				{
-					architecture = "amd64";
-				}
-				else {
-					architecture = Enum.GetName(typeof(ImageFileMachine), Platform.Architecture).ToLower();
-				}
-				if (architecture == "i386") architecturePaths = new string[] { "i386", "x86" };
-				if (architecture == "amd64") architecturePaths = new string[] { "amd64", "x64" };
-				if (architecturePaths == null) architecturePaths = new string[] { architecture };
-				Platform.ExpandPaths(libraryPaths, "{Arch}", architecturePaths);
+                string architecture;
+                string[] architecturePaths = null;
+                if (Platform.Architecture == ImageFileMachine.I386 && Environment.Is64BitProcess)
+                {
+                    architecture = "amd64";
+                }
+                else
+                {
+                    architecture = Enum.GetName(typeof(ImageFileMachine), Platform.Architecture).ToLower();
+                }
+                if (architecture == "i386") architecturePaths = new string[] { "i386", "x86" };
+                if (architecture == "amd64") architecturePaths = new string[] { "amd64", "x64" };
+                if (architecturePaths == null) architecturePaths = new string[] { architecture };
+                Platform.ExpandPaths(libraryPaths, "{Arch}", architecturePaths);
 
-				// Now TRY the enumerated Directories for libFile.so.*
+                // Now TRY the enumerated Directories for libFile.so.*
 
-				string traceLabel = string.Format("UnmanagedLibrary[{0}]", libraryName);
+                string traceLabel = string.Format("UnmanagedLibrary[{0}]", libraryName);
 
-				foreach (string libraryPath in libraryPaths)
-				{
-			        string folder = null;
-			        string filesPattern = libraryPath;
-			        int filesPatternI;
-			        if (-1 < (filesPatternI = filesPattern.LastIndexOf('/')))
-			        {
-			            folder = filesPattern.Substring(0, filesPatternI + 1);
-			            filesPattern = filesPattern.Substring(filesPatternI + 1);
-			        }
+                foreach (string libraryPath in libraryPaths)
+                {
+                    string folder = null;
+                    string filesPattern = libraryPath;
+                    int filesPatternI;
+                    if (-1 < (filesPatternI = filesPattern.LastIndexOf('/')))
+                    {
+                        folder = filesPattern.Substring(0, filesPatternI + 1);
+                        filesPattern = filesPattern.Substring(filesPatternI + 1);
+                    }
 
-			        if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) continue;
+                    if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) continue;
 
-			        string[] files = Directory.EnumerateFiles(folder, filesPattern, SearchOption.TopDirectoryOnly).ToArray();
+                    string[] files = Directory.EnumerateFiles(folder, filesPattern, SearchOption.TopDirectoryOnly).ToArray();
 
-				    foreach (string file in files)
-					{
-						// Finally, I am really loading this file
-						SafeLibraryHandle handle = OpenHandle(file);
+                    foreach (string file in files)
+                    {
+                        // Finally, I am really loading this file
+                        SafeLibraryHandle handle = OpenHandle(file);
 
-						if (!handle.IsNullOrInvalid())
-						{
-							if (Platform.IsMono) {
-								// This is Platform.Posix. In mono, just dlopen'ing the library doesn't work.
-								// Using DllImport("__Internal", EntryPoint = "mono_dllmap_insert") to get mono on the path.
-								MonoDllMapInsert(libraryName, file);
-							}
+                        if (!handle.IsNullOrInvalid())
+                        {
+                            if (Platform.IsMono)
+                            {
+                                // This is Platform.Posix. In mono, just dlopen'ing the library doesn't work.
+                                // Using DllImport("__Internal", EntryPoint = "mono_dllmap_insert") to get mono on the path.
+                                MonoDllMapInsert(libraryName, file);
+                            }
 
-							Trace.TraceInformation(string.Format("{0} Loaded binary \"{1}\"", 
-								traceLabel, file));
+                            Trace.TraceInformation(string.Format("{0} Loaded binary \"{1}\"",
+                                traceLabel, file));
 
-							return new UnmanagedLibrary(libraryName, handle);
-						}
+                            return new UnmanagedLibrary(libraryName, handle);
+                        }
 
                         handle.Close();
 
                         Exception nativeEx = GetLastLibraryError();
-						Trace.TraceInformation(string.Format("{0} Custom binary \"{1}\" not loaded: {2}", 
-							traceLabel, file, nativeEx.Message));
-					}					
-				}
+                        Trace.TraceInformation(string.Format("{0} Custom binary \"{1}\" not loaded: {2}",
+                            traceLabel, file, nativeEx.Message));
+                    }
+                }
 
-				// Search ManifestResources for fileName.arch.ext
-				string resourceName = string.Format("ZeroMQ.{0}.{1}{2}", libraryName, architecture, ".so");
-				string tempPath = Path.Combine(Path.GetTempPath(), resourceName);
+                // Search ManifestResources for fileName.arch.ext
+                string resourceName = string.Format("ZeroMQ.{0}.{1}{2}", libraryName, architecture, ".so");
+                string tempPath = Path.Combine(Path.GetTempPath(), resourceName);
 
-				if (ExtractManifestResource(resourceName, tempPath))
-				{
-					// TODO: need syscall_chmod_execute(path); ?
-					SafeLibraryHandle handle = OpenHandle(tempPath);
+                if (ExtractManifestResource(resourceName, tempPath))
+                {
+                    // TODO: need syscall_chmod_execute(path); ?
+                    SafeLibraryHandle handle = OpenHandle(tempPath);
+
+                    if (!handle.IsNullOrInvalid())
+                    {
+                        if (Platform.IsMono) MonoDllMapInsert(libraryName, tempPath);
 
-					if (!handle.IsNullOrInvalid())
-					{
-						if (Platform.IsMono) MonoDllMapInsert(libraryName, tempPath);
+                        Trace.TraceInformation(string.Format("{0} Loaded binary from EmbeddedResource \"{1}\" from \"{2}\".",
+                            traceLabel, resourceName, tempPath));
 
-						Trace.TraceInformation(string.Format("{0} Loaded binary from EmbeddedResource \"{1}\" from \"{2}\".", 
-							traceLabel, resourceName, tempPath));
-						
-						return new UnmanagedLibrary(libraryName, handle);
-					}
+                        return new UnmanagedLibrary(libraryName, handle);
+                    }
 
                     handle.Close();
 
                     Trace.TraceWarning(string.Format("{0} Unable to run the extracted EmbeddedResource \"{1}\" from \"{2}\".",
-						traceLabel, resourceName, tempPath));
-				}
-				else
-				{
-					Trace.TraceWarning(string.Format("{0} Unable to extract the EmbeddedResource \"{1}\" to \"{2}\".",
-						traceLabel, resourceName, tempPath));
-				}
+                        traceLabel, resourceName, tempPath));
+                }
+                else
+                {
+                    Trace.TraceWarning(string.Format("{0} Unable to extract the EmbeddedResource \"{1}\" to \"{2}\".",
+                        traceLabel, resourceName, tempPath));
+                }
 
 
-				var fnf404 = new StringBuilder();
-				fnf404.Append(traceLabel);
-				fnf404.Append(" Unable to load binary \"");
-				fnf404.Append(libraryName);
-				fnf404.AppendLine("\" from folders");
-				foreach (string path in libraryPaths)
-				{
-					fnf404.Append("\t");
-					fnf404.AppendLine(path);
-				}
-				fnf404.Append(" Also unable to load binary from EmbeddedResource \"");
-				fnf404.Append(resourceName);
-				fnf404.Append("\", from temporary path \"");
-				fnf404.Append(tempPath);
-				fnf404.Append("\". See Trace output for more information.");
+                var fnf404 = new StringBuilder();
+                fnf404.Append(traceLabel);
+                fnf404.Append(" Unable to load binary \"");
+                fnf404.Append(libraryName);
+                fnf404.AppendLine("\" from folders");
+                foreach (string path in libraryPaths)
+                {
+                    fnf404.Append("\t");
+                    fnf404.AppendLine(path);
+                }
+                fnf404.Append(" Also unable to load binary from EmbeddedResource \"");
+                fnf404.Append(resourceName);
+                fnf404.Append("\", from temporary path \"");
+                fnf404.Append(tempPath);
+                fnf404.Append("\". See Trace output for more information.");
 
-				throw new FileNotFoundException(fnf404.ToString());
-			}
+                throw new FileNotFoundException(fnf404.ToString());
+            }
 
-			public static string[] EnumerateLibLdConf(string fileName)
-			{
-				if (!File.Exists(fileName)) return null;
-
-				var libLoadConf = new List<string>();
-				using (var fileReader = new StreamReader(fileName))
-				{
-					while (!fileReader.EndOfStream)
-					{
-						string line = fileReader.ReadLine().TrimStart(new char[] { ' ' });
-
-						// Comments
-						if (line.StartsWith("#", StringComparison.OrdinalIgnoreCase)) continue;
-						int commentI;
-						if (-1 < (commentI = line.IndexOf("#")))
-						{
-							// remove Comments
-							line = line.Substring(0, commentI);
-						}
-
-						if (string.IsNullOrWhiteSpace(line.Trim())) continue;
-
-						// Include /etc/ld.so.conf.d/*.conf, say enumerate files
-						if (line.StartsWith("include ", StringComparison.OrdinalIgnoreCase))
-						{
-							string folder = null;
-							string filesPattern = line.Substring("include ".Length);
-							int filesPatternI;
-							if (-1 == (filesPatternI = filesPattern.IndexOf('*')))
-							{
-								filesPatternI = filesPattern.Length;
-							}
-							if (-1 < (filesPatternI = filesPattern.LastIndexOf('/', filesPatternI)))
-							{
-								folder = filesPattern.Substring(0, filesPatternI + 1);
-								filesPattern = filesPattern.Substring(filesPatternI + 1);
-							}
-
-							if (folder == null || !Directory.Exists(folder)) continue;
-
-							string[] files = Directory.EnumerateFiles(folder, filesPattern, SearchOption.TopDirectoryOnly).ToArray();
-
-							foreach (string file in files)
-							{
-								string[] _libLoadConf = EnumerateLibLdConf(file);
-								if (_libLoadConf != null) libLoadConf.AddRange(_libLoadConf);
-							}
-
-							continue;
-						}
-
-						// Folder
-						string path = EnsureNotEndingSlash(line);
-						if (path != null && Directory.Exists(path)) libLoadConf.Add(path);
-					}
-				}
+            public static string[] EnumerateLibLdConf(string fileName)
+            {
+                if (!File.Exists(fileName)) return null;
 
-				return libLoadConf.ToArray();
-			}
+                var libLoadConf = new List<string>();
+                using (var fileReader = new StreamReader(fileName))
+                {
+                    while (!fileReader.EndOfStream)
+                    {
+                        string line = fileReader.ReadLine().TrimStart(new char[] { ' ' });
+
+                        // Comments
+                        if (line.StartsWith("#", StringComparison.OrdinalIgnoreCase)) continue;
+                        int commentI;
+                        if (-1 < (commentI = line.IndexOf("#")))
+                        {
+                            // remove Comments
+                            line = line.Substring(0, commentI);
+                        }
+
+                        if (string.IsNullOrWhiteSpace(line.Trim())) continue;
+
+                        // Include /etc/ld.so.conf.d/*.conf, say enumerate files
+                        if (line.StartsWith("include ", StringComparison.OrdinalIgnoreCase))
+                        {
+                            string folder = null;
+                            string filesPattern = line.Substring("include ".Length);
+                            int filesPatternI;
+                            if (-1 == (filesPatternI = filesPattern.IndexOf('*')))
+                            {
+                                filesPatternI = filesPattern.Length;
+                            }
+                            if (-1 < (filesPatternI = filesPattern.LastIndexOf('/', filesPatternI)))
+                            {
+                                folder = filesPattern.Substring(0, filesPatternI + 1);
+                                filesPattern = filesPattern.Substring(filesPatternI + 1);
+                            }
+
+                            if (folder == null || !Directory.Exists(folder)) continue;
+
+                            string[] files = Directory.EnumerateFiles(folder, filesPattern, SearchOption.TopDirectoryOnly).ToArray();
+
+                            foreach (string file in files)
+                            {
+                                string[] _libLoadConf = EnumerateLibLdConf(file);
+                                if (_libLoadConf != null) libLoadConf.AddRange(_libLoadConf);
+                            }
+
+                            continue;
+                        }
+
+                        // Folder
+                        string path = EnsureNotEndingSlash(line);
+                        if (path != null && Directory.Exists(path)) libLoadConf.Add(path);
+                    }
+                }
+
+                return libLoadConf.ToArray();
+            }
 
             private static IEnumerable<string> EnumerateLibLdPATH()
             {
@@ -315,43 +316,43 @@
             }
 
             private static string EnsureNotEndingSlash(string path)
-			{
-				if (path == null) return null;
-				if (path.EndsWith("/")) return path.Substring(0, path.Length - 1);
-				return path;
-			}
+            {
+                if (path == null) return null;
+                if (path.EndsWith("/")) return path.Substring(0, path.Length - 1);
+                return path;
+            }
 
-			public static SafeLibraryHandle OpenHandle(string fileName)
-			{
-				IntPtr fileNamePtr = Marshal.StringToHGlobalAnsi(fileName);
-				SafeLibraryHandle libHandle = dlopen(fileNamePtr, RTLD_LAZY | RTLD_GLOBAL);
-				Marshal.FreeHGlobal(fileNamePtr);
-				return libHandle;
-			}
+            public static SafeLibraryHandle OpenHandle(string fileName)
+            {
+                IntPtr fileNamePtr = Marshal.StringToHGlobalAnsi(fileName);
+                SafeLibraryHandle libHandle = dlopen(fileNamePtr, RTLD_LAZY | RTLD_GLOBAL);
+                Marshal.FreeHGlobal(fileNamePtr);
+                return libHandle;
+            }
 
-			public static IntPtr LoadProcedure(SafeLibraryHandle libHandle, string functionName)
-			{
-				IntPtr functionNamePtr = Marshal.StringToHGlobalAnsi(functionName);
-				IntPtr procHandle = dlsym(libHandle, functionNamePtr);
-				Marshal.FreeHGlobal(functionNamePtr);
-				return procHandle;
-			}
+            public static IntPtr LoadProcedure(SafeLibraryHandle libHandle, string functionName)
+            {
+                IntPtr functionNamePtr = Marshal.StringToHGlobalAnsi(functionName);
+                IntPtr procHandle = dlsym(libHandle, functionNamePtr);
+                Marshal.FreeHGlobal(functionNamePtr);
+                return procHandle;
+            }
 
-			public static bool ReleaseHandle(IntPtr handle)
-			{
-				return dlclose(handle) == 0;
-			}
+            public static bool ReleaseHandle(IntPtr handle)
+            {
+                return dlclose(handle) == 0;
+            }
 
-			public static Exception GetLastLibraryError()
-			{
-				IntPtr text = dlerror();
-				string strg = null;
-				if (text != IntPtr.Zero)
-				{
-					strg = Marshal.PtrToStringAnsi(text);
-				}
-				return new DllNotFoundException(strg);
-			}
-		}
-	}
+            public static Exception GetLastLibraryError()
+            {
+                IntPtr text = dlerror();
+                string strg = null;
+                if (text != IntPtr.Zero)
+                {
+                    strg = Marshal.PtrToStringAnsi(text);
+                }
+                return new DllNotFoundException(strg);
+            }
+        }
+    }
 }

+ 206 - 205
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/Platform.Win32.cs

@@ -2,221 +2,222 @@
 
 namespace ZeroMQ.lib
 {
-	using System;
-	using System.Collections.Generic;
-	using System.Diagnostics;
-	using System.IO;
-	using System.Linq;
-	using System.Reflection;
-	using System.Runtime.ConstrainedExecution;
-	using System.Runtime.InteropServices;
-
-	public static partial class Platform
-	{
-		public static class Win32
-		{
-			private const string LibraryName = "kernel32";
-
-			// public const string LibraryFileExtension = ".dll";
-
-			public static readonly string[] LibraryPaths = new string[] {
+    using System;
+    using System.Collections.Generic;
+    using System.Diagnostics;
+    using System.IO;
+    using System.Linq;
+    using System.Reflection;
+    using System.Runtime.ConstrainedExecution;
+    using System.Runtime.InteropServices;
+
+    public static partial class Platform
+    {
+        public static class Win32
+        {
+            private const string LibraryName = "kernel32";
+
+            // public const string LibraryFileExtension = ".dll";
+
+            public static readonly string[] LibraryPaths = new string[] {
                 @"{System32}\{LibraryName}.dll",
                 @"{DllPath}\{LibraryName}.dll",
-				@"{AppBase}\{Arch}\{LibraryName}.dll",
+                @"{AppBase}\{Arch}\{LibraryName}.dll",
             };
 
-			[DllImport(LibraryName, CharSet = CharSet.Auto, BestFitMapping = false, SetLastError = true)]
-			private static extern SafeLibraryHandle LoadLibrary(string fileName);
-
-			[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
-			[DllImport(LibraryName, SetLastError = true)]
-			[return: MarshalAs(UnmanagedType.Bool)]
-			private static extern bool FreeLibrary(IntPtr moduleHandle);
-
-			[DllImport(LibraryName)]
-			private static extern IntPtr GetProcAddress(SafeLibraryHandle moduleHandle, string procname);
-
-			public static UnmanagedLibrary LoadUnmanagedLibrary(string libraryName)
-			{
-				if (string.IsNullOrWhiteSpace(libraryName))
-				{
-					throw new ArgumentException("A valid library name is expected.", "libraryName");
-				}
-
-				// Now look: This method should ExpandPaths on LibraryPaths.
-				// That being said, it should just enumerate
-				// Path, AppBase, Arch, Compiler, LibraryName, Extension
-
-				// Secondly, this method should try each /lib/x86_64-linux-gnu/libload.so.2 to load,
-				// Third, this method should try EmbeddedResources,
-				// Finally, this method fails, telling the user all libraryPaths searched.
-
-				var libraryPaths = new List<string>(Platform.LibraryPaths);
-
-				Platform.ExpandPaths(libraryPaths, "{System32}", Environment.SystemDirectory);
-	
-				var PATHs = new List<string>();
-				PATHs.Add(EnsureNotEndingBackSlash(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)));
-				PATHs.AddRange(EnumeratePATH());
-				Platform.ExpandPaths(libraryPaths, "{DllPath}", PATHs);
-
-				Platform.ExpandPaths(libraryPaths, "{AppBase}", EnsureNotEndingBackSlash(
-						AppDomain.CurrentDomain.BaseDirectory));
-
-				Platform.ExpandPaths(libraryPaths, "{LibraryName}", libraryName);
-
-				// Platform.ExpandPaths(libraryPaths, "{Ext}", Platform.LibraryFileExtension);
-
-				string architecture;
-				string[] architecturePaths = null;
-				if (Platform.Architecture == ImageFileMachine.I386 && Environment.Is64BitProcess)
-				{
-					architecture = "amd64";
-				}
-				else {
-					architecture = Enum.GetName(typeof(ImageFileMachine), Platform.Architecture).ToLower();
-				}
-				if (architecture == "i386") architecturePaths = new string[] { "i386", "x86" };
-				if (architecture == "amd64") architecturePaths = new string[] { "amd64", "x64" };
-				if (architecturePaths == null) architecturePaths = new string[] { architecture };
-				Platform.ExpandPaths(libraryPaths, "{Arch}", architecturePaths);
-
-				// Now TRY the enumerated Directories for libFile.so.*
-
-				string traceLabel = string.Format("UnmanagedLibrary[{0}]", libraryName);
-
-				foreach (string libraryPath in libraryPaths)
-				{
-					string folder = null;
-					string filesPattern = libraryPath;
-					int filesPatternI;
-					if (-1 < (filesPatternI = filesPattern.LastIndexOf('\\')))
-					{
-						folder = filesPattern.Substring(0, filesPatternI + 1);
-						filesPattern = filesPattern.Substring(filesPatternI + 1);
-					}
-
-					if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) continue;
-
-					string[] files = Directory.EnumerateFiles(folder, filesPattern, SearchOption.TopDirectoryOnly).ToArray();
-
-					foreach (string file in files)
-					{
-						// Finally, I am really loading this file
-						SafeLibraryHandle handle = OpenHandle(file);
-
-						if (!handle.IsNullOrInvalid())
-						{
-							Trace.TraceInformation(string.Format("{0} Loaded binary \"{1}\"", 
-								traceLabel, file));
-
-							return new UnmanagedLibrary(libraryName, handle);
-						}
+            [DllImport(LibraryName, CharSet = CharSet.Auto, BestFitMapping = false, SetLastError = true)]
+            private static extern SafeLibraryHandle LoadLibrary(string fileName);
+
+            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
+            [DllImport(LibraryName, SetLastError = true)]
+            [return: MarshalAs(UnmanagedType.Bool)]
+            private static extern bool FreeLibrary(IntPtr moduleHandle);
+
+            [DllImport(LibraryName)]
+            private static extern IntPtr GetProcAddress(SafeLibraryHandle moduleHandle, string procname);
+
+            public static UnmanagedLibrary LoadUnmanagedLibrary(string libraryName)
+            {
+                if (string.IsNullOrWhiteSpace(libraryName))
+                {
+                    throw new ArgumentException("A valid library name is expected.", "libraryName");
+                }
+
+                // Now look: This method should ExpandPaths on LibraryPaths.
+                // That being said, it should just enumerate
+                // Path, AppBase, Arch, Compiler, LibraryName, Extension
+
+                // Secondly, this method should try each /lib/x86_64-linux-gnu/libload.so.2 to load,
+                // Third, this method should try EmbeddedResources,
+                // Finally, this method fails, telling the user all libraryPaths searched.
+
+                var libraryPaths = new List<string>(Platform.LibraryPaths);
+
+                Platform.ExpandPaths(libraryPaths, "{System32}", Environment.SystemDirectory);
+
+                var PATHs = new List<string>();
+                PATHs.Add(EnsureNotEndingBackSlash(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)));
+                PATHs.AddRange(EnumeratePATH());
+                Platform.ExpandPaths(libraryPaths, "{DllPath}", PATHs);
+
+                Platform.ExpandPaths(libraryPaths, "{AppBase}", EnsureNotEndingBackSlash(
+                        AppDomain.CurrentDomain.BaseDirectory));
+
+                Platform.ExpandPaths(libraryPaths, "{LibraryName}", libraryName);
+
+                // Platform.ExpandPaths(libraryPaths, "{Ext}", Platform.LibraryFileExtension);
+
+                string architecture;
+                string[] architecturePaths = null;
+                if (Platform.Architecture == ImageFileMachine.I386 && Environment.Is64BitProcess)
+                {
+                    architecture = "amd64";
+                }
+                else
+                {
+                    architecture = Enum.GetName(typeof(ImageFileMachine), Platform.Architecture).ToLower();
+                }
+                if (architecture == "i386") architecturePaths = new string[] { "i386", "x86" };
+                if (architecture == "amd64") architecturePaths = new string[] { "amd64", "x64" };
+                if (architecturePaths == null) architecturePaths = new string[] { architecture };
+                Platform.ExpandPaths(libraryPaths, "{Arch}", architecturePaths);
+
+                // Now TRY the enumerated Directories for libFile.so.*
+
+                string traceLabel = string.Format("UnmanagedLibrary[{0}]", libraryName);
+
+                foreach (string libraryPath in libraryPaths)
+                {
+                    string folder = null;
+                    string filesPattern = libraryPath;
+                    int filesPatternI;
+                    if (-1 < (filesPatternI = filesPattern.LastIndexOf('\\')))
+                    {
+                        folder = filesPattern.Substring(0, filesPatternI + 1);
+                        filesPattern = filesPattern.Substring(filesPatternI + 1);
+                    }
+
+                    if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) continue;
+
+                    string[] files = Directory.EnumerateFiles(folder, filesPattern, SearchOption.TopDirectoryOnly).ToArray();
+
+                    foreach (string file in files)
+                    {
+                        // Finally, I am really loading this file
+                        SafeLibraryHandle handle = OpenHandle(file);
+
+                        if (!handle.IsNullOrInvalid())
+                        {
+                            Trace.TraceInformation(string.Format("{0} Loaded binary \"{1}\"",
+                                traceLabel, file));
+
+                            return new UnmanagedLibrary(libraryName, handle);
+                        }
 
                         handle.Close();
 
                         Exception nativeEx = GetLastLibraryError();
-						Trace.TraceInformation(string.Format("{0} Custom binary \"{1}\" not loaded: {2}", 
-							traceLabel, file, nativeEx.Message));
-					}
-				}
-
-				// Search ManifestResources for fileName.arch.ext
-				string resourceName = string.Format("ZeroMQ.{0}.{1}{2}", libraryName, architecture, ".dll");
-				string tempPath = Path.Combine(Path.GetTempPath(), resourceName);
-
-				if (ExtractManifestResource(resourceName, tempPath))
-				{
-					SafeLibraryHandle handle = OpenHandle(tempPath);
-
-					if (!handle.IsNullOrInvalid())
-					{
-						Trace.TraceInformation(string.Format("{0} Loaded binary from EmbeddedResource \"{1}\" from \"{2}\".", 
-							traceLabel, resourceName, tempPath));
-						
-						return new UnmanagedLibrary(libraryName, handle);
-					}
+                        Trace.TraceInformation(string.Format("{0} Custom binary \"{1}\" not loaded: {2}",
+                            traceLabel, file, nativeEx.Message));
+                    }
+                }
+
+                // Search ManifestResources for fileName.arch.ext
+                string resourceName = string.Format("ZeroMQ.{0}.{1}{2}", libraryName, architecture, ".dll");
+                string tempPath = Path.Combine(Path.GetTempPath(), resourceName);
+
+                if (ExtractManifestResource(resourceName, tempPath))
+                {
+                    SafeLibraryHandle handle = OpenHandle(tempPath);
+
+                    if (!handle.IsNullOrInvalid())
+                    {
+                        Trace.TraceInformation(string.Format("{0} Loaded binary from EmbeddedResource \"{1}\" from \"{2}\".",
+                            traceLabel, resourceName, tempPath));
+
+                        return new UnmanagedLibrary(libraryName, handle);
+                    }
 
                     handle.Close();
 
                     Trace.TraceWarning(string.Format("{0} Unable to run the extracted EmbeddedResource \"{1}\" from \"{2}\".",
-						traceLabel, resourceName, tempPath));
-				}
-				else
-				{
-					Trace.TraceWarning(string.Format("{0} Unable to extract the EmbeddedResource \"{1}\" to \"{2}\".",
-						traceLabel, resourceName, tempPath));
-				}
-
-				var fnf404 = new StringBuilder();
-				fnf404.Append(traceLabel);
-				fnf404.Append(" Unable to load binary \"");
-				fnf404.Append(libraryName);
-				fnf404.AppendLine("\" from folders");
-				foreach (string path in libraryPaths)
-				{
-					fnf404.Append("\t");
-					fnf404.AppendLine(path);
-				}
-				fnf404.Append(" Also unable to load binary from EmbeddedResource \"");
-				fnf404.Append(resourceName);
-				fnf404.Append("\", from temporary path \"");
-				fnf404.Append(tempPath);
-				fnf404.Append("\". See Trace output for more information.");
-
-				throw new FileNotFoundException(fnf404.ToString());
-			}
-
-			public static string[] EnumeratePATH()
-			{
-				string PATH = System.Environment.GetEnvironmentVariable("PATH");
-				if (PATH == null) return new string[] { };
-
-				string[] paths = PATH.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
-
-				var pathList = new List<string>();
-				foreach (string path in paths)
-				{
-					string _path =
-						EnsureNotDoubleQuoted(
-							EnsureNotEndingBackSlash(path));
-					
-					if (_path != null && Directory.Exists(_path)) pathList.Add(_path);
-				}
-				return pathList.ToArray();
-			}
-
-			private static string EnsureNotDoubleQuoted(string path)
-			{
-				if (path == null) return null;
-				return path.Trim(new char[] { '"' });
-			}
-
-			private static string EnsureNotEndingBackSlash(string path)
-			{
-				if (path == null) return null;
-				return path.TrimEnd(new char[] { '\\' });
-			}
-
-			public static SafeLibraryHandle OpenHandle(string filename)
-			{
-				return LoadLibrary(filename);
-			}
-
-			public static IntPtr LoadProcedure(SafeLibraryHandle handle, string functionName)
-			{
-				return GetProcAddress(handle, functionName);
-			}
-
-			public static bool ReleaseHandle(IntPtr handle)
-			{
-				return FreeLibrary(handle);
-			}
-
-			public static Exception GetLastLibraryError()
-			{
-				return new System.ComponentModel.Win32Exception();
-			}
-		}
-	}
+                        traceLabel, resourceName, tempPath));
+                }
+                else
+                {
+                    Trace.TraceWarning(string.Format("{0} Unable to extract the EmbeddedResource \"{1}\" to \"{2}\".",
+                        traceLabel, resourceName, tempPath));
+                }
+
+                var fnf404 = new StringBuilder();
+                fnf404.Append(traceLabel);
+                fnf404.Append(" Unable to load binary \"");
+                fnf404.Append(libraryName);
+                fnf404.AppendLine("\" from folders");
+                foreach (string path in libraryPaths)
+                {
+                    fnf404.Append("\t");
+                    fnf404.AppendLine(path);
+                }
+                fnf404.Append(" Also unable to load binary from EmbeddedResource \"");
+                fnf404.Append(resourceName);
+                fnf404.Append("\", from temporary path \"");
+                fnf404.Append(tempPath);
+                fnf404.Append("\". See Trace output for more information.");
+
+                throw new FileNotFoundException(fnf404.ToString());
+            }
+
+            public static string[] EnumeratePATH()
+            {
+                string PATH = System.Environment.GetEnvironmentVariable("PATH");
+                if (PATH == null) return new string[] { };
+
+                string[] paths = PATH.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
+
+                var pathList = new List<string>();
+                foreach (string path in paths)
+                {
+                    string _path =
+                        EnsureNotDoubleQuoted(
+                            EnsureNotEndingBackSlash(path));
+
+                    if (_path != null && Directory.Exists(_path)) pathList.Add(_path);
+                }
+                return pathList.ToArray();
+            }
+
+            private static string EnsureNotDoubleQuoted(string path)
+            {
+                if (path == null) return null;
+                return path.Trim(new char[] { '"' });
+            }
+
+            private static string EnsureNotEndingBackSlash(string path)
+            {
+                if (path == null) return null;
+                return path.TrimEnd(new char[] { '\\' });
+            }
+
+            public static SafeLibraryHandle OpenHandle(string filename)
+            {
+                return LoadLibrary(filename);
+            }
+
+            public static IntPtr LoadProcedure(SafeLibraryHandle handle, string functionName)
+            {
+                return GetProcAddress(handle, functionName);
+            }
+
+            public static bool ReleaseHandle(IntPtr handle)
+            {
+                return FreeLibrary(handle);
+            }
+
+            public static Exception GetLastLibraryError()
+            {
+                return new System.ComponentModel.Win32Exception();
+            }
+        }
+    }
 }

+ 30 - 31
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/Platform.__Internal.cs

@@ -1,5 +1,4 @@
 using System;
-using System.Reflection;
 
 /* Example: sqlite3.cs
 
@@ -60,34 +59,34 @@ namespace lib
 
 namespace ZeroMQ.lib
 {
-	public static partial class Platform
-	{
-		public static class __Internal
-		{
-			public static UnmanagedLibrary LoadUnmanagedLibrary(string libraryName)
-			{
-				return null;
-			}
-
-			public static SafeLibraryHandle OpenHandle(string fileName)
-			{
-				throw new NotSupportedException();
-			}
-
-			public static IntPtr LoadProcedure(SafeLibraryHandle libHandle, string functionName)
-			{
-				throw new NotSupportedException();
-			}
-
-			public static bool ReleaseHandle(IntPtr handle)
-			{
-				throw new NotSupportedException();
-			}
-
-			public static Exception GetLastLibraryError()
-			{
-				return new NotSupportedException();
-			}
-		}
-	}
+    public static partial class Platform
+    {
+        public static class __Internal
+        {
+            public static UnmanagedLibrary LoadUnmanagedLibrary(string libraryName)
+            {
+                return null;
+            }
+
+            public static SafeLibraryHandle OpenHandle(string fileName)
+            {
+                throw new NotSupportedException();
+            }
+
+            public static IntPtr LoadProcedure(SafeLibraryHandle libHandle, string functionName)
+            {
+                throw new NotSupportedException();
+            }
+
+            public static bool ReleaseHandle(IntPtr handle)
+            {
+                throw new NotSupportedException();
+            }
+
+            public static Exception GetLastLibraryError()
+            {
+                return new NotSupportedException();
+            }
+        }
+    }
 }

+ 294 - 296
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/Platform.cs

@@ -1,14 +1,12 @@
 namespace ZeroMQ.lib
 {
-	using System;
-	using System.Collections.Generic;
-    using System.Diagnostics;
+    using System;
+    using System.Collections.Generic;
     using System.IO;
-	using System.Linq;
-	using System.Reflection;
-	using System.Runtime.InteropServices;
+    using System.Linq;
+    using System.Reflection;
 
-	/* Common CLR type System.Runtime.InteropServices.ImageFileMachine *
+    /* Common CLR type System.Runtime.InteropServices.ImageFileMachine *
 	public enum ImageFileMachine
 	{
 		i386    = 0x014C,
@@ -18,81 +16,81 @@ namespace ZeroMQ.lib
 		
 	} /**/
 
-	public enum PlatformKind : int
-	{
-		__Internal = 0,
-		Posix,
-		Win32,
-	}
+    public enum PlatformKind : int
+    {
+        __Internal = 0,
+        Posix,
+        Win32,
+    }
 
-	public enum PlatformName : int
-	{
-		__Internal = 0,
-		Posix,
-		Windows,
-		MacOSX,
-	}
+    public enum PlatformName : int
+    {
+        __Internal = 0,
+        Posix,
+        Windows,
+        MacOSX,
+    }
 
-	public static partial class Platform
-	{
-		public static readonly string[] Compilers = new string[] {
-			"msvc2008",
-			"msvc2010",
-			"msvc2012",
-			"msvc2013",
-			"msvc2015",
-			"gcc3",
-			"gcc4",
-			"gcc5",
-			"mingw32",
-		};
+    public static partial class Platform
+    {
+        public static readonly string[] Compilers = new string[] {
+            "msvc2008",
+            "msvc2010",
+            "msvc2012",
+            "msvc2013",
+            "msvc2015",
+            "gcc3",
+            "gcc4",
+            "gcc5",
+            "mingw32",
+        };
 
-		public static readonly string LibraryName;
+        public static readonly string LibraryName;
 
-		// public static readonly string LibraryFileExtension;
+        // public static readonly string LibraryFileExtension;
 
-		public static readonly string[] LibraryPaths;
+        public static readonly string[] LibraryPaths;
 
-		public delegate UnmanagedLibrary LoadUnmanagedLibraryDelegate(string libraryName);
-		public static readonly LoadUnmanagedLibraryDelegate LoadUnmanagedLibrary;
+        public delegate UnmanagedLibrary LoadUnmanagedLibraryDelegate(string libraryName);
+        public static readonly LoadUnmanagedLibraryDelegate LoadUnmanagedLibrary;
 
-		public delegate SafeLibraryHandle OpenHandleDelegate(string filename);
-		public static readonly OpenHandleDelegate OpenHandle;
+        public delegate SafeLibraryHandle OpenHandleDelegate(string filename);
+        public static readonly OpenHandleDelegate OpenHandle;
 
-		public delegate IntPtr LoadProcedureDelegate(SafeLibraryHandle handle, string functionName);
-		public static readonly LoadProcedureDelegate LoadProcedure;
+        public delegate IntPtr LoadProcedureDelegate(SafeLibraryHandle handle, string functionName);
+        public static readonly LoadProcedureDelegate LoadProcedure;
 
-		public delegate bool ReleaseHandleDelegate(IntPtr handle);
-		public static readonly ReleaseHandleDelegate ReleaseHandle;
+        public delegate bool ReleaseHandleDelegate(IntPtr handle);
+        public static readonly ReleaseHandleDelegate ReleaseHandle;
 
-		public delegate Exception GetLastLibraryErrorDelegate();
-		public static readonly GetLastLibraryErrorDelegate GetLastLibraryError;
+        public delegate Exception GetLastLibraryErrorDelegate();
+        public static readonly GetLastLibraryErrorDelegate GetLastLibraryError;
 
-		public static readonly bool Is__Internal;
+        public static readonly bool Is__Internal;
 
-		public static readonly PlatformKind Kind;
+        public static readonly PlatformKind Kind;
 
-		public static readonly PlatformName Name;
+        public static readonly PlatformName Name;
 
-		public static readonly ImageFileMachine Architecture;
+        public static readonly ImageFileMachine Architecture;
 
-		public static readonly string Compiler;
+        public static readonly string Compiler;
 
-		static Platform()
-		{
-			PortableExecutableKinds peKinds;
-			typeof(object).Module.GetPEKind(out peKinds, out Architecture);
+        static Platform()
+        {
+            PortableExecutableKinds peKinds;
+            typeof(object).Module.GetPEKind(out peKinds, out Architecture);
 
-			// Version osVersion;
-			switch (Environment.OSVersion.Platform)
-			{
-				case PlatformID.Win32Windows: // Win9x supported?
-				case PlatformID.Win32S: // Win16 NTVDM on Win x86?
-				case PlatformID.Win32NT: // Windows NT
-					Kind = PlatformKind.Win32;
-					Name = PlatformName.Windows;
+            // Version osVersion;
+            switch (Environment.OSVersion.Platform)
+            {
+                case PlatformID.Win32Windows: // Win9x supported?
+                case PlatformID.Win32S: // Win16 NTVDM on Win x86?
+                case PlatformID.Win32NT: // Windows NT
+                    Kind = PlatformKind.Win32;
+                    Name = PlatformName.Windows;
 
-					/* osVersion = Environment.OSVersion.Version;
+                    /* osVersion = Environment.OSVersion.Version;
 					if (osVersion.Major <= 4) {
 						// WinNT 4
 					} else if (osVersion.Major <= 5) {
@@ -105,39 +103,39 @@ namespace ZeroMQ.lib
 						// info: technet .. msdn .. microsoft research
 
 					} */
-					break;
+                    break;
 
-				case PlatformID.WinCE:
-					// case PlatformID.Xbox:
-					Kind = PlatformKind.Win32;
-					Name = PlatformName.Windows;
-					break;
+                case PlatformID.WinCE:
+                    // case PlatformID.Xbox:
+                    Kind = PlatformKind.Win32;
+                    Name = PlatformName.Windows;
+                    break;
 
-				case PlatformID.Unix:
-					// note: current Mono versions still indicate Unix for Mac OS X
-					Kind = PlatformKind.Posix;
-					Name = PlatformName.Posix;
-					break;
+                case PlatformID.Unix:
+                    // note: current Mono versions still indicate Unix for Mac OS X
+                    Kind = PlatformKind.Posix;
+                    Name = PlatformName.Posix;
+                    break;
 
-				case PlatformID.MacOSX:
-					Kind = PlatformKind.Posix;
-					Name = PlatformName.MacOSX;
-					break;
+                case PlatformID.MacOSX:
+                    Kind = PlatformKind.Posix;
+                    Name = PlatformName.MacOSX;
+                    break;
 
-				default:
-					if ((int)Environment.OSVersion.Platform == 128)
-					{
-						// Mono formerly used 128 for MacOSX
-						Kind = PlatformKind.Posix;
-						Name = PlatformName.MacOSX;
-					}
+                default:
+                    if ((int)Environment.OSVersion.Platform == 128)
+                    {
+                        // Mono formerly used 128 for MacOSX
+                        Kind = PlatformKind.Posix;
+                        Name = PlatformName.MacOSX;
+                    }
 
-					break;
-			}
+                    break;
+            }
 
-			// TODO: Detect and distinguish available Compilers and Runtimes
+            // TODO: Detect and distinguish available Compilers and Runtimes
 
-			/* switch (Kind) {
+            /* switch (Kind) {
 
 			case PlatformKind.Windows:
 				LibraryFileNameFormat = Platform.Windows.LibraryFileNameFormat;
@@ -160,212 +158,212 @@ namespace ZeroMQ.lib
 				throw new PlatformNotSupportedException ();
 			} */
 
-			IsMono = Type.GetType("Mono.Runtime") != null;
-
-			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
-			IsMonoTouch = assemblies.Any(a => a.GetName().Name.Equals("MonoTouch", StringComparison.InvariantCultureIgnoreCase));
-			IsMonoMac = assemblies.Any(a => a.GetName().Name.Equals("MonoMac", StringComparison.InvariantCultureIgnoreCase));
-			IsXamarinIOS = assemblies.Any(a => a.GetName().Name.Equals("Xamarin.iOS", StringComparison.InvariantCultureIgnoreCase));
-			IsXamarinAndroid = assemblies.Any(a => a.GetName().Name.Equals("Xamarin.Android", StringComparison.InvariantCultureIgnoreCase));
-
-			if (IsMonoMac)
-			{
-				Kind = PlatformKind.Posix;
-				Name = PlatformName.MacOSX;
-			}
-
-			if (Name == PlatformName.Posix && File.Exists("/System/Library/CoreServices/SystemVersion.plist")) 
-			{
-				Name = PlatformName.MacOSX;
-			}
-
-			if (IsXamarinIOS || IsMonoTouch)
-			{
-				// Kind = PlatformKind.__Internal;
-				// Name = PlatformName.__Internal;
-
-				Is__Internal = true;
-			}
-
-			SetupImplementation(typeof(Platform));
-		}
-
-		public static bool IsMono { get; private set; }
-
-		public static bool IsMonoMac { get; private set; }
-
-		public static bool IsMonoTouch { get; private set; }
-
-		public static bool IsXamarinIOS { get; private set; }
-
-		public static bool IsXamarinAndroid { get; private set; }
-
-		public static void ExpandPaths(IList<string> stream,
-			string extension, string path)
-		{
-			ExpandPaths(stream, extension, path != null ? new string[] { path } : null);
-		}
-
-		public static void ExpandPaths(IList<string> stream,
-			string extension, IEnumerable<string> paths) 
-		{
-			int pathsC = paths == null ? 0 : paths.Count();
-
-			foreach (string libraryPath in stream.ToArray())
-			{
-				if (-1 == libraryPath.IndexOf(extension)) continue;
-
-				int libraryPathI = stream.IndexOf(libraryPath);
-				stream.RemoveAt(libraryPathI);
-
-				if (pathsC == 0)
-				{
-					// just continue, don't Insert them again
-					continue;
-				}
-
-				if (pathsC == 1)
-				{
-					stream.Insert(libraryPathI, libraryPath.Replace(extension, paths.ElementAt(0)));
-					continue;
-				}
-
-				foreach (string realLibraryPath in paths)
-				{
-					stream.Insert(libraryPathI, libraryPath.Replace(extension, realLibraryPath));
-					++libraryPathI;
-				}
-
-			}
-		}
-
-		public static void SetupImplementation(Type platformDependant)
-		{
-			// Baseline by PlatformKind
-			string platformKind = Enum.GetName(typeof(PlatformKind), Platform.Kind);
-			AssignImplementations(platformDependant, platformKind);
-
-			// Overwrite by PlatformName
-			string platformName = Enum.GetName(typeof(PlatformName), Platform.Name);
-			if (platformName != platformKind)
-			{
-				AssignImplementations(platformDependant, platformName);
-			}
-
-            if (Is__Internal) 
-			{
-				AssignImplementations(platformDependant, "__Internal");
-			}
+            IsMono = Type.GetType("Mono.Runtime") != null;
+
+            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
+            IsMonoTouch = assemblies.Any(a => a.GetName().Name.Equals("MonoTouch", StringComparison.InvariantCultureIgnoreCase));
+            IsMonoMac = assemblies.Any(a => a.GetName().Name.Equals("MonoMac", StringComparison.InvariantCultureIgnoreCase));
+            IsXamarinIOS = assemblies.Any(a => a.GetName().Name.Equals("Xamarin.iOS", StringComparison.InvariantCultureIgnoreCase));
+            IsXamarinAndroid = assemblies.Any(a => a.GetName().Name.Equals("Xamarin.Android", StringComparison.InvariantCultureIgnoreCase));
+
+            if (IsMonoMac)
+            {
+                Kind = PlatformKind.Posix;
+                Name = PlatformName.MacOSX;
+            }
+
+            if (Name == PlatformName.Posix && File.Exists("/System/Library/CoreServices/SystemVersion.plist"))
+            {
+                Name = PlatformName.MacOSX;
+            }
+
+            if (IsXamarinIOS || IsMonoTouch)
+            {
+                // Kind = PlatformKind.__Internal;
+                // Name = PlatformName.__Internal;
+
+                Is__Internal = true;
+            }
+
+            SetupImplementation(typeof(Platform));
         }
 
-		private const BindingFlags bindings = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
-
-		private static void AssignImplementations(Type platformDependant, string implementationName)
-		{
-			Type platformImplementation = platformDependant.GetNestedType(implementationName, bindings);
-			// if (platformImplementation == null) return;
-
-			FieldInfo[] fields = platformDependant.GetFields(bindings);
-			foreach (FieldInfo field in fields)
-			{
-				Type fieldType = field.FieldType;
-				string delegateName = fieldType.Name;
-				MethodInfo methodInfo__internal = null;
-				FieldInfo fieldInfo__internal = null;
-
-				// TODO: This is mapping sodium.crypto_box to sodium.crypto_box__Internal. Should we also map them to sodium.__Internal.crypto_box?
-				if (implementationName == "__Internal")
-				{
-					if (delegateName.EndsWith("_delegate"))
-					{
-						// YOU now have
-						// public static readonly crypto_box_delegate box = crypto_box;
-
-						// YOU need
-						// public static readonly crypto_box_delegate box = crypto_box__Internal;
-
-						delegateName = delegateName.Substring(0, delegateName.Length - "_delegate".Length);
-						if (delegateName.Length > 0)
-						{
-							methodInfo__internal = platformDependant.GetMethod(delegateName + "__Internal", bindings);
-						}
-					}
-				}
-				if (methodInfo__internal == null && platformImplementation != null)
-				{
-					if (delegateName.EndsWith("Delegate"))
-					{
-						// YOU now have
-						// public static readonly UnmanagedLibrary LoadUnmanagedLibraryDelegate;
-
-						// YOU need
-						// public static readonly LoadUnmanagedLibraryDelegate LoadUnmanagedLibrary 
-						//     = Platform.__Internal.LoadUnmanagedLibrary;
-
-						delegateName = delegateName.Substring(0, delegateName.Length - "Delegate".Length);
-
-						methodInfo__internal = platformImplementation.GetMethod(delegateName, bindings);
-					}
-					else
-					{
-						methodInfo__internal = platformImplementation.GetMethod(field.Name, bindings);
-					}
-
-					if (methodInfo__internal == null)
-					{
-						fieldInfo__internal = platformImplementation.GetField(field.Name, bindings);
-					}
-				}
-
-				if (methodInfo__internal != null)
-				{
-					var delegat = Delegate.CreateDelegate(fieldType, methodInfo__internal);
-					field.SetValue(null, delegat);
-				}
-				else if (fieldInfo__internal != null)
-				{
-					object value = fieldInfo__internal.GetValue(null);
-					field.SetValue(null, value);
-				}
-				// else { field.SetValue(null, null); }
-			}
-		}
-
-		private static bool ExtractManifestResource(string resourceName, string outputPath)
-		{
-			if (File.Exists(outputPath))
-			{
-				// This is necessary to prevent access conflicts if multiple processes are run from the
-				// same location. The naming scheme implemented in UnmanagedLibrary should ensure that
-				// the correct version is always used.
-				return true;
-			}
-
-			Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
-
-			if (resourceStream == null)
-			{
-				// No manifest resources were compiled into the current assembly. This is likely a 'manual
-				// deployment' situation, so do not throw an exception at this point and allow all deployment
-				// paths to be searched.
-				return false;
-			}
-
-			try
-			{
-				using (FileStream fileStream = File.Create(outputPath))
-				{
-					resourceStream.CopyTo(fileStream);
-				}
-			}
-			catch (UnauthorizedAccessException)
-			{
-				// Caller does not have write permission for the current file
-				return false;
-			}
-
-			return true;
-		}
-
-	}
+        public static bool IsMono { get; private set; }
+
+        public static bool IsMonoMac { get; private set; }
+
+        public static bool IsMonoTouch { get; private set; }
+
+        public static bool IsXamarinIOS { get; private set; }
+
+        public static bool IsXamarinAndroid { get; private set; }
+
+        public static void ExpandPaths(IList<string> stream,
+            string extension, string path)
+        {
+            ExpandPaths(stream, extension, path != null ? new string[] { path } : null);
+        }
+
+        public static void ExpandPaths(IList<string> stream,
+            string extension, IEnumerable<string> paths)
+        {
+            int pathsC = paths == null ? 0 : paths.Count();
+
+            foreach (string libraryPath in stream.ToArray())
+            {
+                if (-1 == libraryPath.IndexOf(extension)) continue;
+
+                int libraryPathI = stream.IndexOf(libraryPath);
+                stream.RemoveAt(libraryPathI);
+
+                if (pathsC == 0)
+                {
+                    // just continue, don't Insert them again
+                    continue;
+                }
+
+                if (pathsC == 1)
+                {
+                    stream.Insert(libraryPathI, libraryPath.Replace(extension, paths.ElementAt(0)));
+                    continue;
+                }
+
+                foreach (string realLibraryPath in paths)
+                {
+                    stream.Insert(libraryPathI, libraryPath.Replace(extension, realLibraryPath));
+                    ++libraryPathI;
+                }
+
+            }
+        }
+
+        public static void SetupImplementation(Type platformDependant)
+        {
+            // Baseline by PlatformKind
+            string platformKind = Enum.GetName(typeof(PlatformKind), Platform.Kind);
+            AssignImplementations(platformDependant, platformKind);
+
+            // Overwrite by PlatformName
+            string platformName = Enum.GetName(typeof(PlatformName), Platform.Name);
+            if (platformName != platformKind)
+            {
+                AssignImplementations(platformDependant, platformName);
+            }
+
+            if (Is__Internal)
+            {
+                AssignImplementations(platformDependant, "__Internal");
+            }
+        }
+
+        private const BindingFlags bindings = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
+
+        private static void AssignImplementations(Type platformDependant, string implementationName)
+        {
+            Type platformImplementation = platformDependant.GetNestedType(implementationName, bindings);
+            // if (platformImplementation == null) return;
+
+            FieldInfo[] fields = platformDependant.GetFields(bindings);
+            foreach (FieldInfo field in fields)
+            {
+                Type fieldType = field.FieldType;
+                string delegateName = fieldType.Name;
+                MethodInfo methodInfo__internal = null;
+                FieldInfo fieldInfo__internal = null;
+
+                // TODO: This is mapping sodium.crypto_box to sodium.crypto_box__Internal. Should we also map them to sodium.__Internal.crypto_box?
+                if (implementationName == "__Internal")
+                {
+                    if (delegateName.EndsWith("_delegate"))
+                    {
+                        // YOU now have
+                        // public static readonly crypto_box_delegate box = crypto_box;
+
+                        // YOU need
+                        // public static readonly crypto_box_delegate box = crypto_box__Internal;
+
+                        delegateName = delegateName.Substring(0, delegateName.Length - "_delegate".Length);
+                        if (delegateName.Length > 0)
+                        {
+                            methodInfo__internal = platformDependant.GetMethod(delegateName + "__Internal", bindings);
+                        }
+                    }
+                }
+                if (methodInfo__internal == null && platformImplementation != null)
+                {
+                    if (delegateName.EndsWith("Delegate"))
+                    {
+                        // YOU now have
+                        // public static readonly UnmanagedLibrary LoadUnmanagedLibraryDelegate;
+
+                        // YOU need
+                        // public static readonly LoadUnmanagedLibraryDelegate LoadUnmanagedLibrary 
+                        //     = Platform.__Internal.LoadUnmanagedLibrary;
+
+                        delegateName = delegateName.Substring(0, delegateName.Length - "Delegate".Length);
+
+                        methodInfo__internal = platformImplementation.GetMethod(delegateName, bindings);
+                    }
+                    else
+                    {
+                        methodInfo__internal = platformImplementation.GetMethod(field.Name, bindings);
+                    }
+
+                    if (methodInfo__internal == null)
+                    {
+                        fieldInfo__internal = platformImplementation.GetField(field.Name, bindings);
+                    }
+                }
+
+                if (methodInfo__internal != null)
+                {
+                    var delegat = Delegate.CreateDelegate(fieldType, methodInfo__internal);
+                    field.SetValue(null, delegat);
+                }
+                else if (fieldInfo__internal != null)
+                {
+                    object value = fieldInfo__internal.GetValue(null);
+                    field.SetValue(null, value);
+                }
+                // else { field.SetValue(null, null); }
+            }
+        }
+
+        private static bool ExtractManifestResource(string resourceName, string outputPath)
+        {
+            if (File.Exists(outputPath))
+            {
+                // This is necessary to prevent access conflicts if multiple processes are run from the
+                // same location. The naming scheme implemented in UnmanagedLibrary should ensure that
+                // the correct version is always used.
+                return true;
+            }
+
+            Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
+
+            if (resourceStream == null)
+            {
+                // No manifest resources were compiled into the current assembly. This is likely a 'manual
+                // deployment' situation, so do not throw an exception at this point and allow all deployment
+                // paths to be searched.
+                return false;
+            }
+
+            try
+            {
+                using (FileStream fileStream = File.Create(outputPath))
+                {
+                    resourceStream.CopyTo(fileStream);
+                }
+            }
+            catch (UnauthorizedAccessException)
+            {
+                // Caller does not have write permission for the current file
+                return false;
+            }
+
+            return true;
+        }
+
+    }
 }

+ 84 - 87
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/UnmanagedLibrary.cs

@@ -1,103 +1,100 @@
 namespace ZeroMQ.lib
 {
-	using System;
-	using System.Diagnostics;
-	using System.IO;
-	using System.Reflection;
-	using System.Runtime.InteropServices;
-	using System.Security.Permissions;
+    using System;
+    using System.Runtime.InteropServices;
+    using System.Security.Permissions;
 
-	/// <summary>
-	/// Safe handle for unmanaged libraries. See http://msdn.microsoft.com/msdnmag/issues/05/10/Reliability/ for more about safe handles.
-	/// </summary>
-	[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
-	public sealed class SafeLibraryHandle
-		: Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
-	{
-		private SafeLibraryHandle()
-			: base(true)
-		{ }
+    /// <summary>
+    /// Safe handle for unmanaged libraries. See http://msdn.microsoft.com/msdnmag/issues/05/10/Reliability/ for more about safe handles.
+    /// </summary>
+    [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
+    public sealed class SafeLibraryHandle
+        : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
+    {
+        private SafeLibraryHandle()
+            : base(true)
+        { }
 
-		protected override bool ReleaseHandle()
-		{
-			return Platform.ReleaseHandle(handle);
-		}
-	}
+        protected override bool ReleaseHandle()
+        {
+            return Platform.ReleaseHandle(handle);
+        }
+    }
 
-	internal static class SafeLibraryHandles
-	{
-		public static bool IsNullOrInvalid(this SafeLibraryHandle handle)
-		{
-			return handle == null || handle.IsInvalid;
-		}
-	}
+    internal static class SafeLibraryHandles
+    {
+        public static bool IsNullOrInvalid(this SafeLibraryHandle handle)
+        {
+            return handle == null || handle.IsInvalid;
+        }
+    }
 
-	/// <summary>
-	/// Utility class to wrap an unmanaged shared lib and be responsible for freeing it.
-	/// </summary>
-	/// <remarks>
-	/// This is a managed wrapper over the native LoadLibrary, GetProcAddress, and FreeLibrary calls on Windows
-	/// and dlopen, dlsym, and dlclose on Posix environments.
-	/// </remarks>
-	public sealed class UnmanagedLibrary : IDisposable
-	{
-		private readonly string TraceLabel;
+    /// <summary>
+    /// Utility class to wrap an unmanaged shared lib and be responsible for freeing it.
+    /// </summary>
+    /// <remarks>
+    /// This is a managed wrapper over the native LoadLibrary, GetProcAddress, and FreeLibrary calls on Windows
+    /// and dlopen, dlsym, and dlclose on Posix environments.
+    /// </remarks>
+    public sealed class UnmanagedLibrary : IDisposable
+    {
+        private readonly string TraceLabel;
 
-		private readonly SafeLibraryHandle _handle;
+        private readonly SafeLibraryHandle _handle;
 
-		internal UnmanagedLibrary(string libraryName, SafeLibraryHandle libraryHandle)
-		{
-			if (string.IsNullOrWhiteSpace(libraryName))
-			{
-				throw new ArgumentException("A valid library name is expected.", "libraryName");
-			}
-			if (libraryHandle.IsNullOrInvalid())
-			{
-				throw new ArgumentNullException("libraryHandle");
-			}
+        internal UnmanagedLibrary(string libraryName, SafeLibraryHandle libraryHandle)
+        {
+            if (string.IsNullOrWhiteSpace(libraryName))
+            {
+                throw new ArgumentException("A valid library name is expected.", "libraryName");
+            }
+            if (libraryHandle.IsNullOrInvalid())
+            {
+                throw new ArgumentNullException("libraryHandle");
+            }
 
-			TraceLabel = string.Format("UnmanagedLibrary[{0}]", libraryName);
+            TraceLabel = string.Format("UnmanagedLibrary[{0}]", libraryName);
 
-			_handle = libraryHandle;
-		}
+            _handle = libraryHandle;
+        }
 
-		/// <summary>
-		/// Dynamically look up a function in the dll via kernel32!GetProcAddress or libdl!dlsym.
-		/// </summary>
-		/// <typeparam name="TDelegate">Delegate type to load</typeparam>
-		/// <param name="functionName">Raw name of the function in the export table.</param>
-		/// <returns>A delegate to the unmanaged function.</returns>
-		/// <exception cref="MissingMethodException">Thrown if the given function name is not found in the library.</exception>
-		/// <remarks>
-		/// GetProcAddress results are valid as long as the dll is not yet unloaded. This
-		/// is very very dangerous to use since you need to ensure that the dll is not unloaded
-		/// until after you're done with any objects implemented by the dll. For example, if you
-		/// get a delegate that then gets an IUnknown implemented by this dll,
-		/// you can not dispose this library until that IUnknown is collected. Else, you may free
-		/// the library and then the CLR may call release on that IUnknown and it will crash.
-		/// </remarks>
-		public TDelegate GetUnmanagedFunction<TDelegate>(string functionName) where TDelegate : class
-		{
-			IntPtr p = Platform.LoadProcedure(_handle, functionName);
+        /// <summary>
+        /// Dynamically look up a function in the dll via kernel32!GetProcAddress or libdl!dlsym.
+        /// </summary>
+        /// <typeparam name="TDelegate">Delegate type to load</typeparam>
+        /// <param name="functionName">Raw name of the function in the export table.</param>
+        /// <returns>A delegate to the unmanaged function.</returns>
+        /// <exception cref="MissingMethodException">Thrown if the given function name is not found in the library.</exception>
+        /// <remarks>
+        /// GetProcAddress results are valid as long as the dll is not yet unloaded. This
+        /// is very very dangerous to use since you need to ensure that the dll is not unloaded
+        /// until after you're done with any objects implemented by the dll. For example, if you
+        /// get a delegate that then gets an IUnknown implemented by this dll,
+        /// you can not dispose this library until that IUnknown is collected. Else, you may free
+        /// the library and then the CLR may call release on that IUnknown and it will crash.
+        /// </remarks>
+        public TDelegate GetUnmanagedFunction<TDelegate>(string functionName) where TDelegate : class
+        {
+            IntPtr p = Platform.LoadProcedure(_handle, functionName);
 
-			if (p == IntPtr.Zero)
-			{
-				throw new MissingMethodException("Unable to find function '" + functionName + "' in dynamically loaded library.");
-			}
+            if (p == IntPtr.Zero)
+            {
+                throw new MissingMethodException("Unable to find function '" + functionName + "' in dynamically loaded library.");
+            }
 
-			// Ideally, we'd just make the constraint on TDelegate be
-			// System.Delegate, but compiler error CS0702 (constrained can't be System.Delegate)
-			// prevents that. So we make the constraint system.object and do the cast from object-->TDelegate.
-			return (TDelegate)(object)Marshal.GetDelegateForFunctionPointer(p, typeof(TDelegate));
-		}
+            // Ideally, we'd just make the constraint on TDelegate be
+            // System.Delegate, but compiler error CS0702 (constrained can't be System.Delegate)
+            // prevents that. So we make the constraint system.object and do the cast from object-->TDelegate.
+            return (TDelegate)(object)Marshal.GetDelegateForFunctionPointer(p, typeof(TDelegate));
+        }
 
-		public void Dispose()
-		{
-			if (_handle != null && !_handle.IsClosed)
-			{
-				_handle.Close();
-			}
-		}
+        public void Dispose()
+        {
+            if (_handle != null && !_handle.IsClosed)
+            {
+                _handle.Close();
+            }
+        }
 
-	}
+    }
 }

+ 408 - 399
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/zmq.cs

@@ -1,33 +1,33 @@
 namespace ZeroMQ.lib
 {
-	using System;
-	using System.Runtime.InteropServices;
+    using System;
+    using System.Runtime.InteropServices;
 
-	public static unsafe class zmq
-	{
-		private const string __Internal = "__Internal";
+    public static unsafe class zmq
+    {
+        private const string __Internal = "__Internal";
 
-		private const CallingConvention CCCdecl = CallingConvention.Cdecl;
+        private const CallingConvention CCCdecl = CallingConvention.Cdecl;
 
-		// Use a const for the library name
-		private const string LibraryName = "libzmq";
+        // Use a const for the library name
+        private const string LibraryName = "libzmq";
 
-		// Hold a handle to the static instance
-		private static readonly UnmanagedLibrary NativeLib;
+        // Hold a handle to the static instance
+        private static readonly UnmanagedLibrary NativeLib;
 
-		// From zmq.h (v3):
-		// typedef struct {unsigned char _ [32];} zmq_msg_t;
-		private static readonly int sizeof_zmq_msg_t_v3 = 32 * Marshal.SizeOf(typeof(byte));
+        // From zmq.h (v3):
+        // typedef struct {unsigned char _ [32];} zmq_msg_t;
+        private static readonly int sizeof_zmq_msg_t_v3 = 32 * Marshal.SizeOf(typeof(byte));
 
-		// From zmq.h (not v4, but v4.2 and later):
-		// typedef struct zmq_msg_t {unsigned char _ [64];} zmq_msg_t;
-		private static readonly int sizeof_zmq_msg_t_v4 = 64 * Marshal.SizeOf(typeof(byte));
+        // From zmq.h (not v4, but v4.2 and later):
+        // typedef struct zmq_msg_t {unsigned char _ [64];} zmq_msg_t;
+        private static readonly int sizeof_zmq_msg_t_v4 = 64 * Marshal.SizeOf(typeof(byte));
 
-		public static readonly int sizeof_zmq_msg_t = sizeof_zmq_msg_t_v4;
+        public static readonly int sizeof_zmq_msg_t = sizeof_zmq_msg_t_v4;
 
-		// The static constructor prepares static readonly fields
-		static zmq()
-		{
+        // The static constructor prepares static readonly fields
+        static zmq()
+        {
 
 #if !NETSTANDARD && !NETCORE
 			// (0) Initialize Library handle
@@ -37,391 +37,400 @@
 			Platform.SetupImplementation(typeof(zmq));
 #endif
 
-			// Set once LibVersion to libversion()
-			int major, minor, patch;
-			version(out major, out minor, out patch);
-			LibraryVersion = new Version(major, minor, patch);
+            // Set once LibVersion to libversion()
+            int major, minor, patch;
+            version(out major, out minor, out patch);
+            LibraryVersion = new Version(major, minor, patch);
 
-			// Trigger static constructor
+            // Trigger static constructor
             // TODO this is also done in the static initializer of ZError. Can this be unified?
-			var noSym = ZSymbol.None;
-
-			if (major >= 4)
-			{
-				// Current Version 4
-
-				// Use default delegate settings from field initializers.
-				// "Compatibility" is done by "disabling" old methods, or "redirecting" to new methods,
-				// so the developer is forced to work against the latest API
-
-				if (minor == 0)
-				{
-					sizeof_zmq_msg_t = sizeof_zmq_msg_t_v3;
-				}
-			}
-			else if (major >= 3)
-			{
-				// Backwards compatibility for v3
-
-				sizeof_zmq_msg_t = sizeof_zmq_msg_t_v3;
-
-				zmq.ctx_shutdown = (ctxPtr) 
-					=> { throw VersionNotSupported("zmq_ctx_shutdown", "v4"); };
-				zmq.msg_gets = (msgPtr, propertyPtr) 
-					=> { throw VersionNotSupported("zmq_msg_gets", "v4"); };
-				zmq.has = (capabilityPtr) 
-					=> { throw VersionNotSupported("zmq_has", "v4"); };
-				zmq.proxy_steerable = (frontendPtr, backendPtr, capturePtr, controlPtr)
-					=> { throw VersionNotSupported("zmq_proxy_steerable", "v4"); };
-				zmq.curve_keypair = (z85_public_key, z85_secret_key) 
-					=> { throw VersionNotSupported("zmq_curve_keypair", "v4"); };
-				zmq.z85_encode = (dest, data, size) 
-					=> { throw VersionNotSupported("zmq_z85_encode", "v4"); };
-				zmq.z85_decode = (dest, data) 
-					=> { throw VersionNotSupported("zmq_z85_decode", "v4"); };
-
-				if (!Platform.Is__Internal) {
-					zmq.ctx_term = zmq.zmq_term;
-				}
-				else {
-					zmq.ctx_term = zmq.zmq_term__Internal;
-				}
-			}
-			else 
-			{ 
-				throw VersionNotSupported(null, ">= v3");
-			}
-		}
-
-		private static NotSupportedException VersionNotSupported(string methodName, string requiredVersion)
-		{
-			return new NotSupportedException(
-				string.Format(
-					"{0}libzmq version not supported. Required version {1}",
-					methodName == null ? string.Empty : methodName + ": ",
-					requiredVersion));
-		}
-
-		// (2) Declare privately the extern entry point
-		[DllImport(LibraryName, EntryPoint = "zmq_version", CallingConvention = CCCdecl)]
-		private static extern void zmq_version(out int major, out int minor, out int patch);
-		[DllImport(__Internal, EntryPoint = "zmq_version", CallingConvention = CCCdecl)]
-		private static extern void zmq_version__Internal(out int major, out int minor, out int patch);
-
-		// (3) Describe the extern function using a delegate
-		public delegate void zmq_version_delegate(out int major, out int minor, out int patch);
-
-		// (4) Save and return the managed delegate to the unmanaged function
-		//     This static readonly field definition allows to be 
-		//     initialized and possibly redirected by the static constructor.
-		//
-		//     By default this is set to the extern function declaration,
-		//     it may be set to the __Internal extern function declaration.
-		public static readonly zmq_version_delegate version = zmq_version;
-
-		public static readonly Version LibraryVersion;
-
-		/* Deprecated. Use zmq_ctx_new instead.
+            var noSym = ZSymbol.None;
+
+            if (major >= 4)
+            {
+                // Current Version 4
+
+                // Use default delegate settings from field initializers.
+                // "Compatibility" is done by "disabling" old methods, or "redirecting" to new methods,
+                // so the developer is forced to work against the latest API
+
+                if (minor == 0)
+                {
+                    sizeof_zmq_msg_t = sizeof_zmq_msg_t_v3;
+                }
+            }
+            else if (major >= 3)
+            {
+                // Backwards compatibility for v3
+
+                sizeof_zmq_msg_t = sizeof_zmq_msg_t_v3;
+
+                zmq.ctx_shutdown = (ctxPtr)
+                    =>
+                { throw VersionNotSupported("zmq_ctx_shutdown", "v4"); };
+                zmq.msg_gets = (msgPtr, propertyPtr)
+                    =>
+                { throw VersionNotSupported("zmq_msg_gets", "v4"); };
+                zmq.has = (capabilityPtr)
+                    =>
+                { throw VersionNotSupported("zmq_has", "v4"); };
+                zmq.proxy_steerable = (frontendPtr, backendPtr, capturePtr, controlPtr)
+                    =>
+                { throw VersionNotSupported("zmq_proxy_steerable", "v4"); };
+                zmq.curve_keypair = (z85_public_key, z85_secret_key)
+                    =>
+                { throw VersionNotSupported("zmq_curve_keypair", "v4"); };
+                zmq.z85_encode = (dest, data, size)
+                    =>
+                { throw VersionNotSupported("zmq_z85_encode", "v4"); };
+                zmq.z85_decode = (dest, data)
+                    =>
+                { throw VersionNotSupported("zmq_z85_decode", "v4"); };
+
+                if (!Platform.Is__Internal)
+                {
+                    zmq.ctx_term = zmq.zmq_term;
+                }
+                else
+                {
+                    zmq.ctx_term = zmq.zmq_term__Internal;
+                }
+            }
+            else
+            {
+                throw VersionNotSupported(null, ">= v3");
+            }
+        }
+
+        private static NotSupportedException VersionNotSupported(string methodName, string requiredVersion)
+        {
+            return new NotSupportedException(
+                string.Format(
+                    "{0}libzmq version not supported. Required version {1}",
+                    methodName == null ? string.Empty : methodName + ": ",
+                    requiredVersion));
+        }
+
+        // (2) Declare privately the extern entry point
+        [DllImport(LibraryName, EntryPoint = "zmq_version", CallingConvention = CCCdecl)]
+        private static extern void zmq_version(out int major, out int minor, out int patch);
+        [DllImport(__Internal, EntryPoint = "zmq_version", CallingConvention = CCCdecl)]
+        private static extern void zmq_version__Internal(out int major, out int minor, out int patch);
+
+        // (3) Describe the extern function using a delegate
+        public delegate void zmq_version_delegate(out int major, out int minor, out int patch);
+
+        // (4) Save and return the managed delegate to the unmanaged function
+        //     This static readonly field definition allows to be 
+        //     initialized and possibly redirected by the static constructor.
+        //
+        //     By default this is set to the extern function declaration,
+        //     it may be set to the __Internal extern function declaration.
+        public static readonly zmq_version_delegate version = zmq_version;
+
+        public static readonly Version LibraryVersion;
+
+        /* Deprecated. Use zmq_ctx_new instead.
 		[DllImport(LibraryName, EntryPoint = "zmq_init", CallingConvention = CCCdecl)]
 		private static extern IntPtr init(int io_threads); /**/
 
-		[DllImport(LibraryName, EntryPoint = "zmq_ctx_new", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_ctx_new();
-		[DllImport(__Internal, EntryPoint = "zmq_ctx_new", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_ctx_new__Internal();
-		public delegate IntPtr zmq_ctx_new_delegate();
-		public static readonly zmq_ctx_new_delegate ctx_new = zmq_ctx_new;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_ctx_get", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_ctx_get(IntPtr context, Int32 option);
-		[DllImport(__Internal, EntryPoint = "zmq_ctx_get", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_ctx_get__Internal(IntPtr context, Int32 option);
-		public delegate Int32 zmq_ctx_get_delegate(IntPtr context, Int32 option);
-		public static readonly zmq_ctx_get_delegate ctx_get = zmq_ctx_get;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_ctx_set", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_ctx_set(IntPtr context, Int32 option, Int32 optval);
-		[DllImport(__Internal, EntryPoint = "zmq_ctx_set", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_ctx_set__Internal(IntPtr context, Int32 option, Int32 optval);
-		public delegate Int32 zmq_ctx_set_delegate(IntPtr context, Int32 option, Int32 optval);
-		public static readonly zmq_ctx_set_delegate ctx_set = zmq_ctx_set;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_ctx_shutdown", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_ctx_shutdown(IntPtr context);
-		[DllImport(__Internal, EntryPoint = "zmq_ctx_shutdown", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_ctx_shutdown__Internal(IntPtr context);
-		public delegate Int32 zmq_ctx_shutdown_delegate(IntPtr context);
-		public static readonly zmq_ctx_shutdown_delegate ctx_shutdown = zmq_ctx_shutdown;
-
-		/* Deprecated. Use zmq_ctx_term instead.
+        [DllImport(LibraryName, EntryPoint = "zmq_ctx_new", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_ctx_new();
+        [DllImport(__Internal, EntryPoint = "zmq_ctx_new", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_ctx_new__Internal();
+        public delegate IntPtr zmq_ctx_new_delegate();
+        public static readonly zmq_ctx_new_delegate ctx_new = zmq_ctx_new;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_ctx_get", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_ctx_get(IntPtr context, Int32 option);
+        [DllImport(__Internal, EntryPoint = "zmq_ctx_get", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_ctx_get__Internal(IntPtr context, Int32 option);
+        public delegate Int32 zmq_ctx_get_delegate(IntPtr context, Int32 option);
+        public static readonly zmq_ctx_get_delegate ctx_get = zmq_ctx_get;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_ctx_set", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_ctx_set(IntPtr context, Int32 option, Int32 optval);
+        [DllImport(__Internal, EntryPoint = "zmq_ctx_set", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_ctx_set__Internal(IntPtr context, Int32 option, Int32 optval);
+        public delegate Int32 zmq_ctx_set_delegate(IntPtr context, Int32 option, Int32 optval);
+        public static readonly zmq_ctx_set_delegate ctx_set = zmq_ctx_set;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_ctx_shutdown", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_ctx_shutdown(IntPtr context);
+        [DllImport(__Internal, EntryPoint = "zmq_ctx_shutdown", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_ctx_shutdown__Internal(IntPtr context);
+        public delegate Int32 zmq_ctx_shutdown_delegate(IntPtr context);
+        public static readonly zmq_ctx_shutdown_delegate ctx_shutdown = zmq_ctx_shutdown;
+
+        /* Deprecated. Use zmq_ctx_term instead.
 		[DllImport(LibraryName, CallingConvention = CCCdecl)]
 		private static extern Int32 zmq_term(IntPtr context); /**/
 
-		/* Deprecated. Use zmq_ctx_term instead. */
-		[DllImport(LibraryName, EntryPoint = "zmq_term", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_term(IntPtr context);
-		[DllImport(__Internal, EntryPoint = "zmq_term", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_term__Internal(IntPtr context);
-
-		[DllImport(LibraryName, EntryPoint = "zmq_ctx_term", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_ctx_term(IntPtr context);
-		[DllImport(__Internal, EntryPoint = "zmq_ctx_term", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_ctx_term__Internal(IntPtr context);
-		public delegate Int32 zmq_ctx_term_delegate(IntPtr context);
-		public static readonly zmq_ctx_term_delegate ctx_term = zmq_ctx_term;
-
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_init", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_init(IntPtr msg);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_init", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_init__Internal(IntPtr msg);
-		public delegate Int32 zmq_msg_init_delegate(IntPtr msg);
-		public static readonly zmq_msg_init_delegate msg_init = zmq_msg_init;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_init_size", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_init_size(IntPtr msg, Int32 size);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_init_size", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_init_size__Internal(IntPtr msg, Int32 size);
-		public delegate Int32 zmq_msg_init_size_delegate(IntPtr msg, Int32 size);
-		public static readonly zmq_msg_init_size_delegate msg_init_size = zmq_msg_init_size;
-
-		[UnmanagedFunctionPointer(CCCdecl)]
-		public delegate void FreeMessageDataDelegate(IntPtr data, IntPtr hint);
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_init_data", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_init_data(IntPtr msg, IntPtr data, Int32 size, FreeMessageDataDelegate ffn, IntPtr hint);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_init_data", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_init_data__Internal(IntPtr msg, IntPtr data, Int32 size, FreeMessageDataDelegate ffn, IntPtr hint);
-		public delegate Int32 zmq_msg_init_data_delegate(IntPtr msg, IntPtr data, Int32 size, FreeMessageDataDelegate ffn, IntPtr hint);
-		public static readonly zmq_msg_init_data_delegate msg_init_data = zmq_msg_init_data;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_send", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_send(IntPtr msg, IntPtr socket, Int32 flags);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_send", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_send__Internal(IntPtr msg, IntPtr socket, Int32 flags);
-		public delegate Int32 zmq_msg_send_delegate(IntPtr msg, IntPtr socket, Int32 flags);
-		public static readonly zmq_msg_send_delegate msg_send = zmq_msg_send;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_recv", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_recv(IntPtr msg, IntPtr socket, Int32 flags);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_recv", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_recv__Internal(IntPtr msg, IntPtr socket, Int32 flags);
-		public delegate Int32 zmq_msg_recv_delegate(IntPtr msg, IntPtr socket, Int32 flags);
-		public static readonly zmq_msg_recv_delegate msg_recv = zmq_msg_recv;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_close", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_close(IntPtr msg);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_close", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_close__Internal(IntPtr msg);
-		public delegate Int32 zmq_msg_close_delegate(IntPtr msg);
-		public static readonly zmq_msg_close_delegate msg_close = zmq_msg_close;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_data", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_msg_data(IntPtr msg);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_data", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_msg_data__Internal(IntPtr msg);
-		public delegate IntPtr zmq_msg_data_delegate(IntPtr msg);
-		public static readonly zmq_msg_data_delegate msg_data = zmq_msg_data;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_size", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_size(IntPtr msg);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_size", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_size__Internal(IntPtr msg);
-		public delegate Int32 zmq_msg_size_delegate(IntPtr msg);
-		public static readonly zmq_msg_size_delegate msg_size = zmq_msg_size;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_more", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_more(IntPtr msg);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_more", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_more__Internal(IntPtr msg);
-		public delegate Int32 zmq_msg_more_delegate(IntPtr msg);
-		public static readonly zmq_msg_more_delegate msg_more = zmq_msg_more;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_gets", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_msg_gets(IntPtr msg, IntPtr property);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_gets", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_msg_gets__Internal(IntPtr msg, IntPtr property);
-		public delegate IntPtr zmq_msg_gets_delegate(IntPtr msg, IntPtr property);
-		public static readonly zmq_msg_gets_delegate msg_gets = zmq_msg_gets;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_get", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_get(IntPtr msg, Int32 property);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_get", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_get__Internal(IntPtr msg, Int32 property);
-		public delegate Int32 zmq_msg_get_delegate(IntPtr msg, Int32 property);
-		public static readonly zmq_msg_get_delegate msg_get = zmq_msg_get;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_set", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_set(IntPtr msg, Int32 property, Int32 value);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_set", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_set__Internal(IntPtr msg, Int32 property, Int32 value);
-		public delegate Int32 zmq_msg_set_delegate(IntPtr msg, Int32 property, Int32 value);
-		public static readonly zmq_msg_set_delegate msg_set = zmq_msg_set;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_copy", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_copy(IntPtr dest, IntPtr src);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_copy", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_copy__Internal(IntPtr dest, IntPtr src);
-		public delegate Int32 zmq_msg_copy_delegate(IntPtr dest, IntPtr src);
-		public static readonly zmq_msg_copy_delegate msg_copy = zmq_msg_copy;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_msg_move", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_move(IntPtr dest, IntPtr src);
-		[DllImport(__Internal, EntryPoint = "zmq_msg_move", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_msg_move__Internal(IntPtr dest, IntPtr src);
-		public delegate Int32 zmq_msg_move_delegate(IntPtr dest, IntPtr src);
-		public static readonly zmq_msg_move_delegate msg_move = zmq_msg_move;
-
-
-		[DllImport(LibraryName, EntryPoint = "zmq_socket", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_socket(IntPtr context, Int32 type);
-		[DllImport(__Internal, EntryPoint = "zmq_socket", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_socket__Internal(IntPtr context, Int32 type);
-		public delegate IntPtr zmq_socket_delegate(IntPtr context, Int32 type);
-		public static readonly zmq_socket_delegate socket = zmq_socket;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_close", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_close(IntPtr socket);
-		[DllImport(__Internal, EntryPoint = "zmq_close", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_close__Internal(IntPtr socket);
-		public delegate Int32 zmq_close_delegate(IntPtr socket);
-		public static readonly zmq_close_delegate close = zmq_close;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_getsockopt", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_getsockopt(IntPtr socket, Int32 option_name, IntPtr option_value, IntPtr option_len);
-		[DllImport(__Internal, EntryPoint = "zmq_getsockopt", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_getsockopt__Internal(IntPtr socket, Int32 option_name, IntPtr option_value, IntPtr option_len);
-		public delegate Int32 zmq_getsockopt_delegate(IntPtr socket, Int32 option_name, IntPtr option_value, IntPtr option_len);
-		public static readonly zmq_getsockopt_delegate getsockopt = zmq_getsockopt;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_setsockopt", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_setsockopt(IntPtr socket, Int32 option_name, IntPtr option_value, Int32 option_len);
-		[DllImport(__Internal, EntryPoint = "zmq_setsockopt", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_setsockopt__Internal(IntPtr socket, Int32 option_name, IntPtr option_value, Int32 option_len);
-		public delegate Int32 zmq_setsockopt_delegate(IntPtr socket, Int32 option_name, IntPtr option_value, Int32 option_len);
-		public static readonly zmq_setsockopt_delegate setsockopt = zmq_setsockopt;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_bind", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_bind(IntPtr socket, IntPtr endpoint);
-		[DllImport(__Internal, EntryPoint = "zmq_bind", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_bind__Internal(IntPtr socket, IntPtr endpoint);
-		public delegate Int32 zmq_bind_delegate(IntPtr socket, IntPtr endpoint);
-		public static readonly zmq_bind_delegate bind = zmq_bind;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_unbind", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_unbind(IntPtr socket, IntPtr endpoint);
-		[DllImport(__Internal, EntryPoint = "zmq_unbind", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_unbind__Internal(IntPtr socket, IntPtr endpoint);
-		public delegate Int32 zmq_unbind_delegate(IntPtr socket, IntPtr endpoint);
-		public static readonly zmq_unbind_delegate unbind = zmq_unbind;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_connect", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_connect(IntPtr socket, IntPtr endpoint);
-		[DllImport(__Internal, EntryPoint = "zmq_connect", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_connect__Internal(IntPtr socket, IntPtr endpoint);
-		public delegate Int32 zmq_connect_delegate(IntPtr socket, IntPtr endpoint);
-		public static readonly zmq_connect_delegate connect = zmq_connect;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_disconnect", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_disconnect(IntPtr socket, IntPtr endpoint);
-		[DllImport(__Internal, EntryPoint = "zmq_disconnect", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_disconnect__Internal(IntPtr socket, IntPtr endpoint);
-		public delegate Int32 zmq_disconnect_delegate(IntPtr socket, IntPtr endpoint);
-		public static readonly zmq_disconnect_delegate disconnect = zmq_disconnect;
-
-		// Using void* to be liberal for zmq_pollitem_windows_t and _posix_t
-		[DllImport(LibraryName, EntryPoint = "zmq_poll", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_poll(void* items, Int32 numItems, long timeout);
-		[DllImport(__Internal, EntryPoint = "zmq_poll", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_poll__Internal(void* items, Int32 numItems, long timeout);
-		// private static extern Int32 zmq_poll(IntPtr items, Int32 numItems, long timeout);
-		public delegate Int32 zmq_poll_delegate(void* items, Int32 numItems, long timeout);
-		public static readonly zmq_poll_delegate poll = zmq_poll;
-
-
-		[DllImport(LibraryName, EntryPoint = "zmq_send", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_send(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
-		[DllImport(__Internal, EntryPoint = "zmq_send", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_send__Internal(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
-		public delegate Int32 zmq_send_delegate(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
-		public static readonly zmq_send_delegate send = zmq_send;
-
-		// [DllImport(LibraryName, CallingConvention = CCCdecl)]
-		// private static extern Int32 zmq_send_const(IntPtr socket, IntPtr buf, Int32 size, Int32 flags);
-
-		[DllImport(LibraryName, EntryPoint = "zmq_recv", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_recv(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
-		[DllImport(__Internal, EntryPoint = "zmq_recv", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_recv__Internal(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
-		public delegate Int32 zmq_recv_delegate(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
-		public static readonly zmq_recv_delegate recv = zmq_recv;
-
-
-		[DllImport(LibraryName, EntryPoint = "zmq_has", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_has(IntPtr capability);
-		[DllImport(__Internal, EntryPoint = "zmq_has", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_has__Internal(IntPtr capability);
-		public delegate Int32 zmq_has_delegate(IntPtr capability);
-		public static readonly zmq_has_delegate has = zmq_has;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_socket_monitor", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_socket_monitor(IntPtr socket, IntPtr endpoint, Int32 events);
-		[DllImport(__Internal, EntryPoint = "zmq_socket_monitor", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_socket_monitor__Internal(IntPtr socket, IntPtr endpoint, Int32 events);
-		public delegate Int32 zmq_socket_monitor_delegate(IntPtr socket, IntPtr endpoint, Int32 events);
-		public static readonly zmq_socket_monitor_delegate socket_monitor = zmq_socket_monitor;
-
-
-		[DllImport(LibraryName, EntryPoint = "zmq_proxy", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_proxy(IntPtr frontend, IntPtr backend, IntPtr capture);
-		[DllImport(__Internal, EntryPoint = "zmq_proxy", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_proxy__Internal(IntPtr frontend, IntPtr backend, IntPtr capture);
-		public delegate Int32 zmq_proxy_delegate(IntPtr frontend, IntPtr backend, IntPtr capture);
-		public static readonly zmq_proxy_delegate proxy = zmq_proxy;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_proxy_steerable", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_proxy_steerable(IntPtr frontend, IntPtr backend, IntPtr capture, IntPtr control);
-		[DllImport(__Internal, EntryPoint = "zmq_proxy_steerable", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_proxy_steerable__Internal(IntPtr frontend, IntPtr backend, IntPtr capture, IntPtr control);
-		public delegate Int32 zmq_proxy_steerable_delegate(IntPtr frontend, IntPtr backend, IntPtr capture, IntPtr control);
-		public static readonly zmq_proxy_steerable_delegate proxy_steerable = zmq_proxy_steerable;
-
-
-		[DllImport(LibraryName, EntryPoint = "zmq_curve_keypair", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_curve_keypair(IntPtr z85_public_key, IntPtr z85_secret_key);
-		[DllImport(__Internal, EntryPoint = "zmq_curve_keypair", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_curve_keypair__Internal(IntPtr z85_public_key, IntPtr z85_secret_key);
-		public delegate Int32 zmq_curve_keypair_delegate(IntPtr z85_public_key, IntPtr z85_secret_key);
-		public static readonly zmq_curve_keypair_delegate curve_keypair = zmq_curve_keypair;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_z85_encode", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_z85_encode(IntPtr dest, IntPtr data, Int32 size);
-		[DllImport(__Internal, EntryPoint = "zmq_z85_encode", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_z85_encode__Internal(IntPtr dest, IntPtr data, Int32 size);
-		public delegate IntPtr zmq_z85_encode_delegate(IntPtr dest, IntPtr data, Int32 size);
-		public static readonly zmq_z85_encode_delegate z85_encode = zmq_z85_encode;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_z85_decode", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_z85_decode(IntPtr dest, IntPtr data);
-		[DllImport(__Internal, EntryPoint = "zmq_z85_decode", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_z85_decode__Internal(IntPtr dest, IntPtr data);
-		public delegate IntPtr zmq_z85_decode_delegate(IntPtr dest, IntPtr data);
-		public static readonly zmq_z85_decode_delegate z85_decode = zmq_z85_decode;
-
-
-		[DllImport(LibraryName, EntryPoint = "zmq_errno", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_errno();
-		[DllImport(__Internal, EntryPoint = "zmq_errno", CallingConvention = CCCdecl)]
-		private static extern Int32 zmq_errno__Internal();
-		public delegate Int32 zmq_errno_delegate();
-		public static readonly zmq_errno_delegate errno = zmq_errno;
-
-		[DllImport(LibraryName, EntryPoint = "zmq_strerror", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_strerror(int errnum);
-		[DllImport(__Internal, EntryPoint = "zmq_strerror", CallingConvention = CCCdecl)]
-		private static extern IntPtr zmq_strerror__Internal(int errnum);
-		public delegate IntPtr zmq_strerror_delegate(int errnum);
-		public static readonly zmq_strerror_delegate strerror = zmq_strerror;
-
-	}
+        /* Deprecated. Use zmq_ctx_term instead. */
+        [DllImport(LibraryName, EntryPoint = "zmq_term", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_term(IntPtr context);
+        [DllImport(__Internal, EntryPoint = "zmq_term", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_term__Internal(IntPtr context);
+
+        [DllImport(LibraryName, EntryPoint = "zmq_ctx_term", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_ctx_term(IntPtr context);
+        [DllImport(__Internal, EntryPoint = "zmq_ctx_term", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_ctx_term__Internal(IntPtr context);
+        public delegate Int32 zmq_ctx_term_delegate(IntPtr context);
+        public static readonly zmq_ctx_term_delegate ctx_term = zmq_ctx_term;
+
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_init", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_init(IntPtr msg);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_init", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_init__Internal(IntPtr msg);
+        public delegate Int32 zmq_msg_init_delegate(IntPtr msg);
+        public static readonly zmq_msg_init_delegate msg_init = zmq_msg_init;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_init_size", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_init_size(IntPtr msg, Int32 size);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_init_size", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_init_size__Internal(IntPtr msg, Int32 size);
+        public delegate Int32 zmq_msg_init_size_delegate(IntPtr msg, Int32 size);
+        public static readonly zmq_msg_init_size_delegate msg_init_size = zmq_msg_init_size;
+
+        [UnmanagedFunctionPointer(CCCdecl)]
+        public delegate void FreeMessageDataDelegate(IntPtr data, IntPtr hint);
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_init_data", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_init_data(IntPtr msg, IntPtr data, Int32 size, FreeMessageDataDelegate ffn, IntPtr hint);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_init_data", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_init_data__Internal(IntPtr msg, IntPtr data, Int32 size, FreeMessageDataDelegate ffn, IntPtr hint);
+        public delegate Int32 zmq_msg_init_data_delegate(IntPtr msg, IntPtr data, Int32 size, FreeMessageDataDelegate ffn, IntPtr hint);
+        public static readonly zmq_msg_init_data_delegate msg_init_data = zmq_msg_init_data;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_send", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_send(IntPtr msg, IntPtr socket, Int32 flags);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_send", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_send__Internal(IntPtr msg, IntPtr socket, Int32 flags);
+        public delegate Int32 zmq_msg_send_delegate(IntPtr msg, IntPtr socket, Int32 flags);
+        public static readonly zmq_msg_send_delegate msg_send = zmq_msg_send;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_recv", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_recv(IntPtr msg, IntPtr socket, Int32 flags);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_recv", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_recv__Internal(IntPtr msg, IntPtr socket, Int32 flags);
+        public delegate Int32 zmq_msg_recv_delegate(IntPtr msg, IntPtr socket, Int32 flags);
+        public static readonly zmq_msg_recv_delegate msg_recv = zmq_msg_recv;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_close", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_close(IntPtr msg);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_close", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_close__Internal(IntPtr msg);
+        public delegate Int32 zmq_msg_close_delegate(IntPtr msg);
+        public static readonly zmq_msg_close_delegate msg_close = zmq_msg_close;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_data", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_msg_data(IntPtr msg);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_data", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_msg_data__Internal(IntPtr msg);
+        public delegate IntPtr zmq_msg_data_delegate(IntPtr msg);
+        public static readonly zmq_msg_data_delegate msg_data = zmq_msg_data;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_size", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_size(IntPtr msg);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_size", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_size__Internal(IntPtr msg);
+        public delegate Int32 zmq_msg_size_delegate(IntPtr msg);
+        public static readonly zmq_msg_size_delegate msg_size = zmq_msg_size;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_more", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_more(IntPtr msg);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_more", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_more__Internal(IntPtr msg);
+        public delegate Int32 zmq_msg_more_delegate(IntPtr msg);
+        public static readonly zmq_msg_more_delegate msg_more = zmq_msg_more;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_gets", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_msg_gets(IntPtr msg, IntPtr property);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_gets", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_msg_gets__Internal(IntPtr msg, IntPtr property);
+        public delegate IntPtr zmq_msg_gets_delegate(IntPtr msg, IntPtr property);
+        public static readonly zmq_msg_gets_delegate msg_gets = zmq_msg_gets;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_get", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_get(IntPtr msg, Int32 property);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_get", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_get__Internal(IntPtr msg, Int32 property);
+        public delegate Int32 zmq_msg_get_delegate(IntPtr msg, Int32 property);
+        public static readonly zmq_msg_get_delegate msg_get = zmq_msg_get;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_set", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_set(IntPtr msg, Int32 property, Int32 value);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_set", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_set__Internal(IntPtr msg, Int32 property, Int32 value);
+        public delegate Int32 zmq_msg_set_delegate(IntPtr msg, Int32 property, Int32 value);
+        public static readonly zmq_msg_set_delegate msg_set = zmq_msg_set;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_copy", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_copy(IntPtr dest, IntPtr src);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_copy", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_copy__Internal(IntPtr dest, IntPtr src);
+        public delegate Int32 zmq_msg_copy_delegate(IntPtr dest, IntPtr src);
+        public static readonly zmq_msg_copy_delegate msg_copy = zmq_msg_copy;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_msg_move", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_move(IntPtr dest, IntPtr src);
+        [DllImport(__Internal, EntryPoint = "zmq_msg_move", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_msg_move__Internal(IntPtr dest, IntPtr src);
+        public delegate Int32 zmq_msg_move_delegate(IntPtr dest, IntPtr src);
+        public static readonly zmq_msg_move_delegate msg_move = zmq_msg_move;
+
+
+        [DllImport(LibraryName, EntryPoint = "zmq_socket", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_socket(IntPtr context, Int32 type);
+        [DllImport(__Internal, EntryPoint = "zmq_socket", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_socket__Internal(IntPtr context, Int32 type);
+        public delegate IntPtr zmq_socket_delegate(IntPtr context, Int32 type);
+        public static readonly zmq_socket_delegate socket = zmq_socket;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_close", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_close(IntPtr socket);
+        [DllImport(__Internal, EntryPoint = "zmq_close", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_close__Internal(IntPtr socket);
+        public delegate Int32 zmq_close_delegate(IntPtr socket);
+        public static readonly zmq_close_delegate close = zmq_close;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_getsockopt", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_getsockopt(IntPtr socket, Int32 option_name, IntPtr option_value, IntPtr option_len);
+        [DllImport(__Internal, EntryPoint = "zmq_getsockopt", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_getsockopt__Internal(IntPtr socket, Int32 option_name, IntPtr option_value, IntPtr option_len);
+        public delegate Int32 zmq_getsockopt_delegate(IntPtr socket, Int32 option_name, IntPtr option_value, IntPtr option_len);
+        public static readonly zmq_getsockopt_delegate getsockopt = zmq_getsockopt;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_setsockopt", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_setsockopt(IntPtr socket, Int32 option_name, IntPtr option_value, Int32 option_len);
+        [DllImport(__Internal, EntryPoint = "zmq_setsockopt", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_setsockopt__Internal(IntPtr socket, Int32 option_name, IntPtr option_value, Int32 option_len);
+        public delegate Int32 zmq_setsockopt_delegate(IntPtr socket, Int32 option_name, IntPtr option_value, Int32 option_len);
+        public static readonly zmq_setsockopt_delegate setsockopt = zmq_setsockopt;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_bind", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_bind(IntPtr socket, IntPtr endpoint);
+        [DllImport(__Internal, EntryPoint = "zmq_bind", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_bind__Internal(IntPtr socket, IntPtr endpoint);
+        public delegate Int32 zmq_bind_delegate(IntPtr socket, IntPtr endpoint);
+        public static readonly zmq_bind_delegate bind = zmq_bind;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_unbind", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_unbind(IntPtr socket, IntPtr endpoint);
+        [DllImport(__Internal, EntryPoint = "zmq_unbind", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_unbind__Internal(IntPtr socket, IntPtr endpoint);
+        public delegate Int32 zmq_unbind_delegate(IntPtr socket, IntPtr endpoint);
+        public static readonly zmq_unbind_delegate unbind = zmq_unbind;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_connect", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_connect(IntPtr socket, IntPtr endpoint);
+        [DllImport(__Internal, EntryPoint = "zmq_connect", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_connect__Internal(IntPtr socket, IntPtr endpoint);
+        public delegate Int32 zmq_connect_delegate(IntPtr socket, IntPtr endpoint);
+        public static readonly zmq_connect_delegate connect = zmq_connect;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_disconnect", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_disconnect(IntPtr socket, IntPtr endpoint);
+        [DllImport(__Internal, EntryPoint = "zmq_disconnect", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_disconnect__Internal(IntPtr socket, IntPtr endpoint);
+        public delegate Int32 zmq_disconnect_delegate(IntPtr socket, IntPtr endpoint);
+        public static readonly zmq_disconnect_delegate disconnect = zmq_disconnect;
+
+        // Using void* to be liberal for zmq_pollitem_windows_t and _posix_t
+        [DllImport(LibraryName, EntryPoint = "zmq_poll", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_poll(void* items, Int32 numItems, long timeout);
+        [DllImport(__Internal, EntryPoint = "zmq_poll", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_poll__Internal(void* items, Int32 numItems, long timeout);
+        // private static extern Int32 zmq_poll(IntPtr items, Int32 numItems, long timeout);
+        public delegate Int32 zmq_poll_delegate(void* items, Int32 numItems, long timeout);
+        public static readonly zmq_poll_delegate poll = zmq_poll;
+
+
+        [DllImport(LibraryName, EntryPoint = "zmq_send", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_send(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
+        [DllImport(__Internal, EntryPoint = "zmq_send", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_send__Internal(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
+        public delegate Int32 zmq_send_delegate(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
+        public static readonly zmq_send_delegate send = zmq_send;
+
+        // [DllImport(LibraryName, CallingConvention = CCCdecl)]
+        // private static extern Int32 zmq_send_const(IntPtr socket, IntPtr buf, Int32 size, Int32 flags);
+
+        [DllImport(LibraryName, EntryPoint = "zmq_recv", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_recv(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
+        [DllImport(__Internal, EntryPoint = "zmq_recv", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_recv__Internal(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
+        public delegate Int32 zmq_recv_delegate(IntPtr socket, IntPtr buf, Int32 len, Int32 flags);
+        public static readonly zmq_recv_delegate recv = zmq_recv;
+
+
+        [DllImport(LibraryName, EntryPoint = "zmq_has", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_has(IntPtr capability);
+        [DllImport(__Internal, EntryPoint = "zmq_has", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_has__Internal(IntPtr capability);
+        public delegate Int32 zmq_has_delegate(IntPtr capability);
+        public static readonly zmq_has_delegate has = zmq_has;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_socket_monitor", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_socket_monitor(IntPtr socket, IntPtr endpoint, Int32 events);
+        [DllImport(__Internal, EntryPoint = "zmq_socket_monitor", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_socket_monitor__Internal(IntPtr socket, IntPtr endpoint, Int32 events);
+        public delegate Int32 zmq_socket_monitor_delegate(IntPtr socket, IntPtr endpoint, Int32 events);
+        public static readonly zmq_socket_monitor_delegate socket_monitor = zmq_socket_monitor;
+
+
+        [DllImport(LibraryName, EntryPoint = "zmq_proxy", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_proxy(IntPtr frontend, IntPtr backend, IntPtr capture);
+        [DllImport(__Internal, EntryPoint = "zmq_proxy", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_proxy__Internal(IntPtr frontend, IntPtr backend, IntPtr capture);
+        public delegate Int32 zmq_proxy_delegate(IntPtr frontend, IntPtr backend, IntPtr capture);
+        public static readonly zmq_proxy_delegate proxy = zmq_proxy;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_proxy_steerable", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_proxy_steerable(IntPtr frontend, IntPtr backend, IntPtr capture, IntPtr control);
+        [DllImport(__Internal, EntryPoint = "zmq_proxy_steerable", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_proxy_steerable__Internal(IntPtr frontend, IntPtr backend, IntPtr capture, IntPtr control);
+        public delegate Int32 zmq_proxy_steerable_delegate(IntPtr frontend, IntPtr backend, IntPtr capture, IntPtr control);
+        public static readonly zmq_proxy_steerable_delegate proxy_steerable = zmq_proxy_steerable;
+
+
+        [DllImport(LibraryName, EntryPoint = "zmq_curve_keypair", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_curve_keypair(IntPtr z85_public_key, IntPtr z85_secret_key);
+        [DllImport(__Internal, EntryPoint = "zmq_curve_keypair", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_curve_keypair__Internal(IntPtr z85_public_key, IntPtr z85_secret_key);
+        public delegate Int32 zmq_curve_keypair_delegate(IntPtr z85_public_key, IntPtr z85_secret_key);
+        public static readonly zmq_curve_keypair_delegate curve_keypair = zmq_curve_keypair;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_z85_encode", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_z85_encode(IntPtr dest, IntPtr data, Int32 size);
+        [DllImport(__Internal, EntryPoint = "zmq_z85_encode", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_z85_encode__Internal(IntPtr dest, IntPtr data, Int32 size);
+        public delegate IntPtr zmq_z85_encode_delegate(IntPtr dest, IntPtr data, Int32 size);
+        public static readonly zmq_z85_encode_delegate z85_encode = zmq_z85_encode;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_z85_decode", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_z85_decode(IntPtr dest, IntPtr data);
+        [DllImport(__Internal, EntryPoint = "zmq_z85_decode", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_z85_decode__Internal(IntPtr dest, IntPtr data);
+        public delegate IntPtr zmq_z85_decode_delegate(IntPtr dest, IntPtr data);
+        public static readonly zmq_z85_decode_delegate z85_decode = zmq_z85_decode;
+
+
+        [DllImport(LibraryName, EntryPoint = "zmq_errno", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_errno();
+        [DllImport(__Internal, EntryPoint = "zmq_errno", CallingConvention = CCCdecl)]
+        private static extern Int32 zmq_errno__Internal();
+        public delegate Int32 zmq_errno_delegate();
+        public static readonly zmq_errno_delegate errno = zmq_errno;
+
+        [DllImport(LibraryName, EntryPoint = "zmq_strerror", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_strerror(int errnum);
+        [DllImport(__Internal, EntryPoint = "zmq_strerror", CallingConvention = CCCdecl)]
+        private static extern IntPtr zmq_strerror__Internal(int errnum);
+        public delegate IntPtr zmq_strerror_delegate(int errnum);
+        public static readonly zmq_strerror_delegate strerror = zmq_strerror;
+
+    }
 }

+ 41 - 41
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/zmq_pollitem_posix_t.cs

@@ -1,51 +1,51 @@
 namespace ZeroMQ.lib
 {
-	using System;
-	using System.Runtime.InteropServices;
+    using System;
+    using System.Runtime.InteropServices;
 
-	[StructLayout(LayoutKind.Sequential)]
-	public struct zmq_pollitem_posix_t // : zmq_pollitem_i
-	{
-		private IntPtr socketPtr;
-		private int fileDescriptor; // POSIX fd is an Int32
-		private short events;
-		private short readyEvents;
+    [StructLayout(LayoutKind.Sequential)]
+    public struct zmq_pollitem_posix_t // : zmq_pollitem_i
+    {
+        private IntPtr socketPtr;
+        private int fileDescriptor; // POSIX fd is an Int32
+        private short events;
+        private short readyEvents;
 
-		public zmq_pollitem_posix_t(IntPtr socket, ZPoll pollEvents)
-		{
-			if (socket == IntPtr.Zero)
-			{
-				throw new ArgumentException("Expected a valid socket handle.", "socket");
-			}
+        public zmq_pollitem_posix_t(IntPtr socket, ZPoll pollEvents)
+        {
+            if (socket == IntPtr.Zero)
+            {
+                throw new ArgumentException("Expected a valid socket handle.", "socket");
+            }
 
-			socketPtr = socket;
-			fileDescriptor = 0;
-			events = (short)pollEvents;
-			readyEvents = (short)ZPoll.None;
-		}
+            socketPtr = socket;
+            fileDescriptor = 0;
+            events = (short)pollEvents;
+            readyEvents = (short)ZPoll.None;
+        }
 
-		public IntPtr SocketPtr
-		{
-			get { return socketPtr; }
-			set { socketPtr = value; }
-		}
+        public IntPtr SocketPtr
+        {
+            get { return socketPtr; }
+            set { socketPtr = value; }
+        }
 
-		public int FileDescriptor
-		{
-			get { return fileDescriptor; }
-			set { fileDescriptor = value; }
-		}
+        public int FileDescriptor
+        {
+            get { return fileDescriptor; }
+            set { fileDescriptor = value; }
+        }
 
-		public short Events
-		{
-			get { return events; }
-			set { events = value; }
-		}
+        public short Events
+        {
+            get { return events; }
+            set { events = value; }
+        }
 
-		public short ReadyEvents
-		{
-			get { return readyEvents; }
-			set { readyEvents = value; }
-		}
-	}
+        public short ReadyEvents
+        {
+            get { return readyEvents; }
+            set { readyEvents = value; }
+        }
+    }
 }

+ 41 - 41
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Platform/zmq_pollitem_windows_t.cs

@@ -1,51 +1,51 @@
 namespace ZeroMQ.lib
 {
-	using System;
-	using System.Runtime.InteropServices;
+    using System;
+    using System.Runtime.InteropServices;
 
-	[StructLayout(LayoutKind.Sequential)]
-	public struct zmq_pollitem_windows_t // : zmq_pollitem_i
-	{
-		private IntPtr socketPtr;
-		private IntPtr fileDescriptor; // Windows is an size_t
-		private short events;
-		private short readyEvents;
+    [StructLayout(LayoutKind.Sequential)]
+    public struct zmq_pollitem_windows_t // : zmq_pollitem_i
+    {
+        private IntPtr socketPtr;
+        private IntPtr fileDescriptor; // Windows is an size_t
+        private short events;
+        private short readyEvents;
 
-		public zmq_pollitem_windows_t(IntPtr socket, ZPoll pollEvents)
-		{
-			if (socket == IntPtr.Zero)
-			{
-				throw new ArgumentException("Expected a valid socket handle.", "socket");
-			}
+        public zmq_pollitem_windows_t(IntPtr socket, ZPoll pollEvents)
+        {
+            if (socket == IntPtr.Zero)
+            {
+                throw new ArgumentException("Expected a valid socket handle.", "socket");
+            }
 
-			socketPtr = socket;
-			fileDescriptor = IntPtr.Zero;
-			events = (short)pollEvents;
-			readyEvents = 0;
-		}
+            socketPtr = socket;
+            fileDescriptor = IntPtr.Zero;
+            events = (short)pollEvents;
+            readyEvents = 0;
+        }
 
-		public IntPtr SocketPtr
-		{
-			get { return socketPtr; }
-			set { socketPtr = value; }
-		}
+        public IntPtr SocketPtr
+        {
+            get { return socketPtr; }
+            set { socketPtr = value; }
+        }
 
-		public IntPtr FileDescriptor
-		{
-			get { return fileDescriptor; }
-			set { fileDescriptor = value; }
-		}
+        public IntPtr FileDescriptor
+        {
+            get { return fileDescriptor; }
+            set { fileDescriptor = value; }
+        }
 
-		public short Events
-		{
-			get { return events; }
-			set { events = value; }
-		}
+        public short Events
+        {
+            get { return events; }
+            set { events = value; }
+        }
 
-		public short ReadyEvents
-		{
-			get { return readyEvents; }
-			set { readyEvents = value; }
-		}
-	}
+        public short ReadyEvents
+        {
+            get { return readyEvents; }
+            set { readyEvents = value; }
+        }
+    }
 }

+ 16 - 16
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/RouterMandatory.cs

@@ -1,20 +1,20 @@
 namespace ZeroMQ
 {
-	/// <summary>
-	/// Specifies <see cref="ZSocketType.ROUTER"/> socket behavior when
-	/// an unroutable message is encountered.
-	/// </summary>
-	public enum RouterMandatory
-	{
-		/// <summary>
-		/// Silently discard messages.
-		/// </summary>
-		Discard = 0,
+    /// <summary>
+    /// Specifies <see cref="ZSocketType.ROUTER"/> socket behavior when
+    /// an unroutable message is encountered.
+    /// </summary>
+    public enum RouterMandatory
+    {
+        /// <summary>
+        /// Silently discard messages.
+        /// </summary>
+        Discard = 0,
 
-		/// <summary>
-		/// Force sending to fail with an 'EAGAIN' error code, effectively
-		/// enabling blocking sends.
-		/// </summary>
-		Report = 1,
-	}
+        /// <summary>
+        /// Force sending to fail with an 'EAGAIN' error code, effectively
+        /// enabling blocking sends.
+        /// </summary>
+        Report = 1,
+    }
 }

+ 18 - 18
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/TcpKeepaliveBehaviour.cs

@@ -1,23 +1,23 @@
 namespace ZeroMQ
 {
-	/// <summary>
-	/// Keep-alive packets behavior for a <see cref="ZSocket"/> connection.
-	/// </summary>
-	public enum TcpKeepaliveBehaviour : int
-	{
-		/// <summary>
-		/// Use Operating System default behavior.
-		/// </summary>
-		Default = -1,
+    /// <summary>
+    /// Keep-alive packets behavior for a <see cref="ZSocket"/> connection.
+    /// </summary>
+    public enum TcpKeepaliveBehaviour : int
+    {
+        /// <summary>
+        /// Use Operating System default behavior.
+        /// </summary>
+        Default = -1,
 
-		/// <summary>
-		/// Disable keep-alive packets.
-		/// </summary>
-		Disable = 0,
+        /// <summary>
+        /// Disable keep-alive packets.
+        /// </summary>
+        Disable = 0,
 
-		/// <summary>
-		/// Enable keep-alive packets.
-		/// </summary>
-		Enable = 1,
-	}
+        /// <summary>
+        /// Enable keep-alive packets.
+        /// </summary>
+        Enable = 1,
+    }
 }

+ 155 - 154
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/Z85.cs

@@ -1,167 +1,168 @@
 using System;
 using System.Runtime.InteropServices;
 using System.Text;
+
 using ZeroMQ.lib;
 
 namespace ZeroMQ
 {
-	public static class Z85
-	{
-		public static void CurveKeypair(out byte[] publicKey, out byte[] secretKey)
-		{
-			const int destLen = 40;
-			using (var publicKeyData = DispoIntPtr.Alloc(destLen + 1))
-			using (var secretKeyData = DispoIntPtr.Alloc(destLen + 1))
-			{
-				if (0 != zmq.curve_keypair(publicKeyData, secretKeyData))
-				{
-					throw new InvalidOperationException();
-				}
-				
-				publicKey = new byte[destLen];
-				Marshal.Copy(publicKeyData, publicKey, 0, destLen);
-				
-				secretKey = new byte[destLen];
-				Marshal.Copy(secretKeyData, secretKey, 0, destLen);
-			}
-		}
-
-		public static byte[] Encode(byte[] decoded)
-		{
-			int dataLen = decoded.Length;
-			if (dataLen % 4 > 0)
-			{
-				throw new InvalidOperationException("decoded.Length must be divisible by 4");
-			}
-			int destLen = (Int32)(decoded.Length * 1.25);
-
-			var data = GCHandle.Alloc(decoded, GCHandleType.Pinned);
+    public static class Z85
+    {
+        public static void CurveKeypair(out byte[] publicKey, out byte[] secretKey)
+        {
+            const int destLen = 40;
+            using (var publicKeyData = DispoIntPtr.Alloc(destLen + 1))
+            using (var secretKeyData = DispoIntPtr.Alloc(destLen + 1))
+            {
+                if (0 != zmq.curve_keypair(publicKeyData, secretKeyData))
+                {
+                    throw new InvalidOperationException();
+                }
+
+                publicKey = new byte[destLen];
+                Marshal.Copy(publicKeyData, publicKey, 0, destLen);
+
+                secretKey = new byte[destLen];
+                Marshal.Copy(secretKeyData, secretKey, 0, destLen);
+            }
+        }
+
+        public static byte[] Encode(byte[] decoded)
+        {
+            int dataLen = decoded.Length;
+            if (dataLen % 4 > 0)
+            {
+                throw new InvalidOperationException("decoded.Length must be divisible by 4");
+            }
+            int destLen = (Int32)(decoded.Length * 1.25);
+
+            var data = GCHandle.Alloc(decoded, GCHandleType.Pinned);
 
             // the buffer dest must be one byte larger than destLen to accomodate the null termination character
-			using (var dest = DispoIntPtr.Alloc(destLen + 1))
-			{
+            using (var dest = DispoIntPtr.Alloc(destLen + 1))
+            {
                 zmq.z85_encode(dest, data.AddrOfPinnedObject(), dataLen);
-				data.Free();
-
-				var bytes = new byte[destLen];
-				Marshal.Copy(dest, bytes, 0, destLen);
-				return bytes;
-			}
-		}
-
-		public static byte[] ToZ85Encoded(this byte[] decoded) 
-		{
-			return Encode(decoded);
-		}
-
-		public static string ToZ85Encoded(this string decoded) 
-		{
-			return Encode(decoded, ZContext.Encoding);
-		}
-
-		public static string ToZ85Encoded(this string decoded, Encoding encoding) 
-		{
-			return Encode(decoded, encoding);
-		}
-
-		public static byte[] ToZ85EncodedBytes(this string decoded) 
-		{
-			return EncodeBytes(decoded, ZContext.Encoding);
-		}
-
-		public static byte[] ToZ85EncodedBytes(this string decoded, Encoding encoding) 
-		{
-			return EncodeBytes(decoded, encoding);
-		}
-
-		public static string Encode(string strg)
-		{
-			return Encode(strg, ZContext.Encoding);
-		}
-
-		public static string Encode(string strg, Encoding encoding)
-		{
-			byte[] encoded = EncodeBytes(strg, encoding);
-			return encoding.GetString(encoded);
-		}
-
-		public static byte[] EncodeBytes(string strg)
-		{
-			return EncodeBytes(strg, ZContext.Encoding);
-		}
-
-		public static byte[] EncodeBytes(string strg, Encoding encoding)
-		{
-			byte[] bytes = encoding.GetBytes(strg);
-			return Encode(bytes);
-		}
-
-
-		public static byte[] Decode(byte[] encoded)
-		{
-			int dataLen = encoded.Length;
-			if (dataLen % 5 > 0)
-			{
-				throw new InvalidOperationException("encoded.Length must be divisible by 5");
-			}
-			int destLen = (Int32)(encoded.Length * .8);
-
-			var data = GCHandle.Alloc(encoded, GCHandleType.Pinned);
-
-			using (var dest = DispoIntPtr.Alloc(destLen))
-			{
+                data.Free();
+
+                var bytes = new byte[destLen];
+                Marshal.Copy(dest, bytes, 0, destLen);
+                return bytes;
+            }
+        }
+
+        public static byte[] ToZ85Encoded(this byte[] decoded)
+        {
+            return Encode(decoded);
+        }
+
+        public static string ToZ85Encoded(this string decoded)
+        {
+            return Encode(decoded, ZContext.Encoding);
+        }
+
+        public static string ToZ85Encoded(this string decoded, Encoding encoding)
+        {
+            return Encode(decoded, encoding);
+        }
+
+        public static byte[] ToZ85EncodedBytes(this string decoded)
+        {
+            return EncodeBytes(decoded, ZContext.Encoding);
+        }
+
+        public static byte[] ToZ85EncodedBytes(this string decoded, Encoding encoding)
+        {
+            return EncodeBytes(decoded, encoding);
+        }
+
+        public static string Encode(string strg)
+        {
+            return Encode(strg, ZContext.Encoding);
+        }
+
+        public static string Encode(string strg, Encoding encoding)
+        {
+            byte[] encoded = EncodeBytes(strg, encoding);
+            return encoding.GetString(encoded);
+        }
+
+        public static byte[] EncodeBytes(string strg)
+        {
+            return EncodeBytes(strg, ZContext.Encoding);
+        }
+
+        public static byte[] EncodeBytes(string strg, Encoding encoding)
+        {
+            byte[] bytes = encoding.GetBytes(strg);
+            return Encode(bytes);
+        }
+
+
+        public static byte[] Decode(byte[] encoded)
+        {
+            int dataLen = encoded.Length;
+            if (dataLen % 5 > 0)
+            {
+                throw new InvalidOperationException("encoded.Length must be divisible by 5");
+            }
+            int destLen = (Int32)(encoded.Length * .8);
+
+            var data = GCHandle.Alloc(encoded, GCHandleType.Pinned);
+
+            using (var dest = DispoIntPtr.Alloc(destLen))
+            {
                 zmq.z85_decode(dest, data.AddrOfPinnedObject());
-				data.Free();
-
-				var decoded = new byte[destLen];
-
-				Marshal.Copy(dest, decoded, 0, decoded.Length);
-
-				return decoded;
-			}
-		}
-
-		public static byte[] ToZ85Decoded(this byte[] encoded) 
-		{
-			return Decode(encoded);
-		}
-
-		public static string ToZ85Decoded(this string encoded) 
-		{
-			return Decode(encoded, ZContext.Encoding);
-		}
-
-		public static string ToZ85Decoded(this string encoded, Encoding encoding) 
-		{
-			return Decode(encoded, encoding);
-		}
-
-		public static byte[] ToZ85DecodedBytes(this string encoded) 
-		{
-			return DecodeBytes(encoded, ZContext.Encoding);
-		}
-
-		public static byte[] ToZ85DecodedBytes(this string encoded, Encoding encoding) 
-		{
-			return DecodeBytes(encoded, encoding);
-		}
-
-		public static string Decode(string strg)
-		{
-			return Decode(strg, ZContext.Encoding);
-		}
-
-		public static string Decode(string strg, Encoding encoding)
-		{
-			byte[] encoded = DecodeBytes(strg, encoding);
-			return encoding.GetString(encoded);
-		}
-		
-		public static byte[] DecodeBytes(string strg, Encoding encoding)
-		{
-			byte[] bytes = encoding.GetBytes(strg);
-			return Decode(bytes);
-		}
-	}
+                data.Free();
+
+                var decoded = new byte[destLen];
+
+                Marshal.Copy(dest, decoded, 0, decoded.Length);
+
+                return decoded;
+            }
+        }
+
+        public static byte[] ToZ85Decoded(this byte[] encoded)
+        {
+            return Decode(encoded);
+        }
+
+        public static string ToZ85Decoded(this string encoded)
+        {
+            return Decode(encoded, ZContext.Encoding);
+        }
+
+        public static string ToZ85Decoded(this string encoded, Encoding encoding)
+        {
+            return Decode(encoded, encoding);
+        }
+
+        public static byte[] ToZ85DecodedBytes(this string encoded)
+        {
+            return DecodeBytes(encoded, ZContext.Encoding);
+        }
+
+        public static byte[] ToZ85DecodedBytes(this string encoded, Encoding encoding)
+        {
+            return DecodeBytes(encoded, encoding);
+        }
+
+        public static string Decode(string strg)
+        {
+            return Decode(strg, ZContext.Encoding);
+        }
+
+        public static string Decode(string strg, Encoding encoding)
+        {
+            byte[] encoded = DecodeBytes(strg, encoding);
+            return encoding.GetString(encoded);
+        }
+
+        public static byte[] DecodeBytes(string strg, Encoding encoding)
+        {
+            byte[] bytes = encoding.GetBytes(strg);
+            return Decode(bytes);
+        }
+    }
 }
 

+ 110 - 112
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/ZActor.cs

@@ -1,114 +1,112 @@
-using System;
-
-namespace ZeroMQ
+namespace ZeroMQ
 {
-	public delegate void ZAction0(ZSocket backend, System.Threading.CancellationTokenSource cancellor, object[] args);
-
-	public delegate void ZAction(ZContext context, ZSocket backend, System.Threading.CancellationTokenSource cancellor, object[] args);
-
-	public class ZActor : ZThread
-	{
-		public ZContext Context { get; protected set; }
-
-		public string Endpoint { get; protected set; }
-
-		public ZAction Action { get; protected set; }
-
-		public ZAction0 Action0 { get; protected set; }
-
-		public object[] Arguments { get; protected set; }
-
-		public ZSocket Backend { get; protected set; }
-
-		public ZSocket Frontend { get; protected set; }
-
-		public ZActor(ZContext context, ZAction action, params object[] args)
-			: this(context, default(string), action, args)
-		{
-			var rnd0 = new byte[8];
-			using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) rng.GetNonZeroBytes(rnd0);
-			this.Endpoint = string.Format("inproc://{0}", ZContext.Encoding.GetString(rnd0));
-		}
-
-		public ZActor(ZContext context, string endpoint, ZAction action, params object[] args)
-			: base()
-		{
-			this.Context = context;
-
-			this.Endpoint = endpoint;
-			this.Action = action;
-			this.Arguments = args;
-		}
-
-		/// <summary>
-		/// You are using ZContext.Current!
-		/// </summary>
-		public ZActor(ZAction0 action, params object[] args)
-			: this(default(string), action, args)
-		{
-			var rnd0 = new byte[8];
-			using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) rng.GetNonZeroBytes(rnd0);
-			this.Endpoint = string.Format("inproc://{0}", ZContext.Encoding.GetString(rnd0));
-		}
-
-		/// <summary>
-		/// You are using ZContext.Current!
-		/// </summary>
-		public ZActor(string endpoint, ZAction0 action, params object[] args)
-			: base()
-		{
-			this.Context = ZContext.Current;
-
-			this.Endpoint = endpoint;
-			this.Action0 = action;
-			this.Arguments = args;
-		}
-
-		protected override void Run()
-		{
-			using (Backend = ZSocket.Create(Context, ZSocketType.PAIR))
-			{
-				Backend.Bind(Endpoint);
-
-				if (Action0 != null)
-				{
-					Action0(Backend, Cancellor, Arguments);
-				}
-				if (Action != null)
-				{
-					Action(Context, Backend, Cancellor, Arguments);
-				}
-			}
-		}
-
-		public override void Start()
-		{
-			base.Start();
-
-			if (Frontend == null)
-			{
-				Frontend = ZSocket.Create(Context, ZSocketType.PAIR);
-				Frontend.Connect(Endpoint);
-			}
-		}
-
-		protected override void Dispose(bool disposing)
-		{
-			base.Dispose(disposing);
-
-			if (disposing)
-			{
-				if (Frontend != null)
-				{
-					Frontend.Dispose();
-					Frontend = null;
-				}
-				if (Backend != null)
-				{
-					Backend.Dispose();
-					Backend = null;
-				}
-			}
-		}
-	}
+    public delegate void ZAction0(ZSocket backend, System.Threading.CancellationTokenSource cancellor, object[] args);
+
+    public delegate void ZAction(ZContext context, ZSocket backend, System.Threading.CancellationTokenSource cancellor, object[] args);
+
+    public class ZActor : ZThread
+    {
+        public ZContext Context { get; protected set; }
+
+        public string Endpoint { get; protected set; }
+
+        public ZAction Action { get; protected set; }
+
+        public ZAction0 Action0 { get; protected set; }
+
+        public object[] Arguments { get; protected set; }
+
+        public ZSocket Backend { get; protected set; }
+
+        public ZSocket Frontend { get; protected set; }
+
+        public ZActor(ZContext context, ZAction action, params object[] args)
+            : this(context, default(string), action, args)
+        {
+            var rnd0 = new byte[8];
+            using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) rng.GetNonZeroBytes(rnd0);
+            this.Endpoint = string.Format("inproc://{0}", ZContext.Encoding.GetString(rnd0));
+        }
+
+        public ZActor(ZContext context, string endpoint, ZAction action, params object[] args)
+            : base()
+        {
+            this.Context = context;
+
+            this.Endpoint = endpoint;
+            this.Action = action;
+            this.Arguments = args;
+        }
+
+        /// <summary>
+        /// You are using ZContext.Current!
+        /// </summary>
+        public ZActor(ZAction0 action, params object[] args)
+            : this(default(string), action, args)
+        {
+            var rnd0 = new byte[8];
+            using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) rng.GetNonZeroBytes(rnd0);
+            this.Endpoint = string.Format("inproc://{0}", ZContext.Encoding.GetString(rnd0));
+        }
+
+        /// <summary>
+        /// You are using ZContext.Current!
+        /// </summary>
+        public ZActor(string endpoint, ZAction0 action, params object[] args)
+            : base()
+        {
+            this.Context = ZContext.Current;
+
+            this.Endpoint = endpoint;
+            this.Action0 = action;
+            this.Arguments = args;
+        }
+
+        protected override void Run()
+        {
+            using (Backend = ZSocket.Create(Context, ZSocketType.PAIR))
+            {
+                Backend.Bind(Endpoint);
+
+                if (Action0 != null)
+                {
+                    Action0(Backend, Cancellor, Arguments);
+                }
+                if (Action != null)
+                {
+                    Action(Context, Backend, Cancellor, Arguments);
+                }
+            }
+        }
+
+        public override void Start()
+        {
+            base.Start();
+
+            if (Frontend == null)
+            {
+                Frontend = ZSocket.Create(Context, ZSocketType.PAIR);
+                Frontend.Connect(Endpoint);
+            }
+        }
+
+        protected override void Dispose(bool disposing)
+        {
+            base.Dispose(disposing);
+
+            if (disposing)
+            {
+                if (Frontend != null)
+                {
+                    Frontend.Dispose();
+                    Frontend = null;
+                }
+                if (Backend != null)
+                {
+                    Backend.Dispose();
+                    Backend = null;
+                }
+            }
+        }
+    }
 }

+ 1 - 1
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/ZAuth.cs

@@ -355,7 +355,7 @@ namespace ZeroMQ
             {
                 //s_zap_request_reply(request, "400", "No access", (unsigned char *) "", 0);
                 request.RequestReply("400", "No access", new byte[0]);
-                
+
             }
         }
 

+ 3 - 3
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/ZCert.cs

@@ -57,7 +57,7 @@ namespace ZeroMQ
             private set
             {
                 publicTxt = value.ToCharArray();
-                publicKey = Z85.DecodeBytes(value, Encoding.UTF8);                   
+                publicKey = Z85.DecodeBytes(value, Encoding.UTF8);
             }
         }
 
@@ -71,7 +71,7 @@ namespace ZeroMQ
             private set
             {
                 secretTxt = value.ToCharArray();
-                secretKey = Z85.DecodeBytes(value, Encoding.UTF8);                
+                secretKey = Z85.DecodeBytes(value, Encoding.UTF8);
             }
         }
 
@@ -98,7 +98,7 @@ namespace ZeroMQ
 
             publicTxt = Encoding.UTF8.GetString(Z85.Encode(publicKey)).ToCharArray();
             secretTxt = Encoding.UTF8.GetString(Z85.Encode(secretKey)).ToCharArray();
-            
+
             byte[] e = Z85.Encode(publicTxt.Select(c => (byte)c).ToArray());
         }
 

+ 2 - 4
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/ZCertStore.cs

@@ -1,8 +1,6 @@
-using System;
-using System.Collections.Generic;
+using System.Collections.Generic;
 using System.IO;
 using System.Linq;
-using System.Text;
 
 namespace ZeroMQ
 {
@@ -102,7 +100,7 @@ namespace ZeroMQ
         public void Insert(ZCert cert)
         {
             lock (certs)
-            { 
+            {
                 certs[cert.PublicTxt] = cert;
             }
         }

+ 339 - 340
dotnet/Library/Sers/Sers.CL/Zmq/ThreadWait/clrzmq4-master/ZContext.cs

@@ -1,348 +1,347 @@
 using System;
 using System.Text;
-using System.Threading;
 
 using ZeroMQ.lib;
 
 namespace ZeroMQ
 {
-	/// <summary>
-	/// Creates <see cref="ZSocket"/> instances within a process boundary.
-	/// </summary>
-	public sealed class ZContext : IDisposable
-	{
-		static Encoding _encoding = System.Text.Encoding.UTF8;
-
-		/// <summary>
-		/// Gets and protected sets the default Encoding.
-		/// Note: Do not set the Encoding after ZContext.Create.
-		/// </summary>
-		public static Encoding Encoding
-		{
-			get { return _encoding; }
-		}
-
-		private static readonly object SyncObject = new object();
-
-		private static ZContext _current;
-
-		public static ZContext Current 
-		{
-			get 
-			{
-				if (_current == null)
-				{
-					// INFO: This is the ZContext who is the one, running this program.
-					lock (SyncObject)
-					{
-						if (_current == null)
-						{
-							_current = new ZContext();
-						}
-					}
-				}
-				return _current;
-			}
-		}
-
-		/// <summary>
-		/// Create a <see cref="ZContext"/> instance.
-		/// </summary>
-		/// <returns><see cref="ZContext"/></returns>
-		public ZContext()
-		{
-			_contextPtr = zmq.ctx_new();
-
-			if (_contextPtr == IntPtr.Zero)
-			{
-				throw new InvalidProgramException("zmq_ctx_new");
-			}
-		}
-
-		/// <summary>
-		/// Create a <see cref="ZContext"/> instance.
-		/// </summary>
-		/// <returns><see cref="ZContext"/></returns>
-		public static ZContext Create()
-		{
-			return new ZContext();
-		}
-
-		~ZContext()
-		{
-			Dispose(false);
-		}
-
-		private IntPtr _contextPtr;
-
-		/// <summary>
-		/// Gets a handle to the native ZeroMQ context.
-		/// </summary>
-		public IntPtr ContextPtr
-		{
-			get { return _contextPtr; }
-		}
-
-		public static bool Has(string capability)
-		{
-			using (var capabilityPtr = DispoIntPtr.AllocString(capability))
-			{
-				if (0 < zmq.has(capabilityPtr))
-				{
-					return true;
-				}
-			}
-			return false;
-		}
-
-		public static void Proxy(ZSocket frontend, ZSocket backend)
-		{
-			Proxy(frontend, backend, null);
-		}
-
-		public static bool Proxy(ZSocket frontend, ZSocket backend, out ZError error)
-		{
-			return Proxy(frontend, backend, null, out error);
-		}
-
-		public static void Proxy(ZSocket frontend, ZSocket backend, ZSocket capture)
-		{
-			ZError error;
-			if (!Proxy(frontend, backend, capture, out error))
-			{
-				if (error == ZError.ETERM)
-				{
-					return;	// Interrupted
-				}
-				throw new ZException(error);
-			}
-		}
-
-		public static bool Proxy(ZSocket frontend, ZSocket backend, ZSocket capture, out ZError error)
-		{
-			error = ZError.None;
-
-			while (-1 == zmq.proxy(frontend.SocketPtr, backend.SocketPtr, capture == null ? IntPtr.Zero : capture.SocketPtr))
-			{
-				error = ZError.GetLastErr();
-
-				if (error == ZError.EINTR)
-				{
-					error = default(ZError);
-					continue;
-				}
-				return false;
-			}
-			return true;
-		}
-
-		public static void ProxySteerable(ZSocket frontend, ZSocket backend, ZSocket control)
-		{
-			ProxySteerable(frontend, backend, null, control);
-		}
-
-		public static bool ProxySteerable(ZSocket frontend, ZSocket backend, ZSocket control, out ZError error)
-		{
-			return ProxySteerable(frontend, backend, null, control, out error);
-		}
-
-		public static void ProxySteerable(ZSocket frontend, ZSocket backend, ZSocket capture, ZSocket control)
-		{
-			ZError error;
-			if (!ProxySteerable(frontend, backend, capture, control, out error))
-			{
-				if (error == ZError.ETERM)
-				{
-					return;	// Interrupted
-				}
-				throw new ZException(error);
-			}
-		}
-
-		public static bool ProxySteerable(ZSocket frontend, ZSocket backend, ZSocket capture, ZSocket control, out ZError error)
-		{
-			error = ZError.None;
-
-			while (-1 == zmq.proxy_steerable(frontend.SocketPtr, backend.SocketPtr, capture == null ? IntPtr.Zero : capture.SocketPtr, control == null ? IntPtr.Zero : control.SocketPtr))
-			{
-				error = ZError.GetLastErr();
-
-				if (error == ZError.EINTR)
-				{
-					error = default(ZError);
-					continue;
-				}
-				return false;
-			}
-			return true;
-		}
-
-		public void SetOption(ZContextOption option, int optionValue)
-		{
-			EnsureNotDisposed();
-
-			int rc = zmq.ctx_set(_contextPtr, (Int32)option, optionValue);
-			if (rc == -1)
-			{
-				var error = ZError.GetLastErr();
-
-				if (error == ZError.EINVAL)
-				{
-					throw new ArgumentOutOfRangeException(
-						string.Format("The requested option optionName \"{0}\" is invalid.", option));
-				}
-				throw new ZException(error);
-			}
-		}
-
-		public int GetOption(ZContextOption option)
-		{
-			EnsureNotDisposed();
-
-			int rc = zmq.ctx_get(_contextPtr, (Int32)option);
-			if (rc == -1)
-			{
-				var error = ZError.GetLastErr();
-
-				if (error == ZError.EINVAL)
-				{
-					throw new ArgumentOutOfRangeException(
-						string.Format("The requested option optionName \"{0}\" is invalid.", option));
-				}
-				throw new ZException(error);
-			}
-			return rc;
-		}
-
-		/// <summary>
-		/// Gets or sets the size of the thread pool for the current context (default = 1).
-		/// </summary>
-		public int ThreadPoolSize
-		{
-			get { return GetOption(ZContextOption.IO_THREADS); }
-			set { SetOption(ZContextOption.IO_THREADS, value); }
-		}
-
-		/// <summary>
-		/// Gets or sets the maximum number of sockets for the current context (default = 1024).
-		/// </summary>
-		public int MaxSockets
-		{
-			get { return GetOption(ZContextOption.MAX_SOCKETS); }
-			set { SetOption(ZContextOption.MAX_SOCKETS, value); }
-		}
-
-		/// <summary>
-		/// Gets or sets the supported socket protocol(s) when using TCP transports. (Default = <see cref="ProtocolType.Ipv4Only"/>).
-		/// </summary>
-		public bool IPv6Enabled
-		{
-			get { return GetOption(ZContextOption.IPV6) == 1; }
-			set { SetOption(ZContextOption.IPV6, value ? 1 : 0); }
-		}
-
-		/// <summary>
-		/// Shutdown the ZeroMQ context.
-		/// </summary>
-		public void Shutdown()
-		{
-			ZError error;
-			if (!Shutdown(out error))
-			{
-				throw new ZException(error);
-			}
-		}
-
-		/// <summary>
-		/// Shutdown the ZeroMQ context.
-		/// </summary>
-		public bool Shutdown(out ZError error)
-		{
-			error = default(ZError);
-
-			if (_contextPtr == IntPtr.Zero)
-				return true;
-
-			while (-1 == zmq.ctx_shutdown(_contextPtr))
-			{
-				error = ZError.GetLastErr();
-
-				if (error == ZError.EINTR)
-				{
-					error = default(ZError);
-					continue;
-				}
-
-				// Maybe ZError.EFAULT
-
-				return false;
-			}
-
-			// don't _contextPtr = IntPtr.Zero;
-			return true;
-		}
-
-		/// <summary>
-		/// Terminate the ZeroMQ context.
-		/// </summary>
-		public void Terminate()
-		{
-			ZError error;
-			if (!Terminate(out error))
-			{
-				throw new ZException(error);
-			}
-		}
-
-		/// <summary>
-		/// Terminate the ZeroMQ context.
-		/// </summary>
-		public bool Terminate(out ZError error)
-		{
-			error = ZError.None;
-			if (_contextPtr == IntPtr.Zero)
-				return true;
-
-			while (-1 == zmq.ctx_term(_contextPtr))
-			{
-				error = ZError.GetLastErr();
-
-				if (error == ZError.EINTR)
-				{
-					error = default(ZError);
-					continue;
-				}
-
-				// Maybe ZError.EFAULT
-
-				return false;
-			}
-
-			_contextPtr = IntPtr.Zero;
-			return true;
-		}
-
-		public void Dispose()
-		{
-			GC.SuppressFinalize(this);
-			Dispose(true);
-		}
-
-		void Dispose(bool disposing)
-		{
-			if (disposing)
-			{
-				ZError error;
-				Terminate(out error);
-			}
-		}
-
-		private void EnsureNotDisposed()
-		{
-			if (_contextPtr == IntPtr.Zero)
-			{
-				throw new ObjectDisposedException(GetType().FullName);
-			}
-		}
-	}
+    /// <summary>
+    /// Creates <see cref="ZSocket"/> instances within a process boundary.
+    /// </summary>
+    public sealed class ZContext : IDisposable
+    {
+        static Encoding _encoding = System.Text.Encoding.UTF8;
+
+        /// <summary>
+        /// Gets and protected sets the default Encoding.
+        /// Note: Do not set the Encoding after ZContext.Create.
+        /// </summary>
+        public static Encoding Encoding
+        {
+            get { return _encoding; }
+        }
+
+        private static readonly object SyncObject = new object();
+
+        private static ZContext _current;
+
+        public static ZContext Current
+        {
+            get
+            {
+                if (_current == null)
+                {
+                    // INFO: This is the ZContext who is the one, running this program.
+                    lock (SyncObject)
+                    {
+                        if (_current == null)
+                        {
+                            _current = new ZContext();
+                        }
+                    }
+                }
+                return _current;
+            }
+        }
+
+        /// <summary>
+        /// Create a <see cref="ZContext"/> instance.
+        /// </summary>
+        /// <returns><see cref="ZContext"/></returns>
+        public ZContext()
+        {
+            _contextPtr = zmq.ctx_new();
+
+            if (_contextPtr == IntPtr.Zero)
+            {
+                throw new InvalidProgramException("zmq_ctx_new");
+            }
+        }
+
+        /// <summary>
+        /// Create a <see cref="ZContext"/> instance.
+        /// </summary>
+        /// <returns><see cref="ZContext"/></returns>
+        public static ZContext Create()
+        {
+            return new ZContext();
+        }
+
+        ~ZContext()
+        {
+            Dispose(false);
+        }
+
+        private IntPtr _contextPtr;
+
+        /// <summary>
+        /// Gets a handle to the native ZeroMQ context.
+        /// </summary>
+        public IntPtr ContextPtr
+        {
+            get { return _contextPtr; }
+        }
+
+        public static bool Has(string capability)
+        {
+            using (var capabilityPtr = DispoIntPtr.AllocString(capability))
+            {
+                if (0 < zmq.has(capabilityPtr))
+                {
+                    return true;
+                }
+            }
+            return false;
+        }
+
+        public static void Proxy(ZSocket frontend, ZSocket backend)
+        {
+            Proxy(frontend, backend, null);
+        }
+
+        public static bool Proxy(ZSocket frontend, ZSocket backend, out ZError error)
+        {
+            return Proxy(frontend, backend, null, out error);
+        }
+
+        public static void Proxy(ZSocket frontend, ZSocket backend, ZSocket capture)
+        {
+            ZError error;
+            if (!Proxy(frontend, backend, capture, out error))
+            {
+                if (error == ZError.ETERM)
+                {
+                    return; // Interrupted
+                }
+                throw new ZException(error);
+            }
+        }
+
+        public static bool Proxy(ZSocket frontend, ZSocket backend, ZSocket capture, out ZError error)
+        {
+            error = ZError.None;
+
+            while (-1 == zmq.proxy(frontend.SocketPtr, backend.SocketPtr, capture == null ? IntPtr.Zero : capture.SocketPtr))
+            {
+                error = ZError.GetLastErr();
+
+                if (error == ZError.EINTR)
+                {
+                    error = default(ZError);
+                    continue;
+                }
+                return false;
+            }
+            return true;
+        }
+
+        public static void ProxySteerable(ZSocket frontend, ZSocket backend, ZSocket control)
+        {
+            ProxySteerable(frontend, backend, null, control);
+        }
+
+        public static bool ProxySteerable(ZSocket frontend, ZSocket backend, ZSocket control, out ZError error)
+        {
+            return ProxySteerable(frontend, backend, null, control, out error);
+        }
+
+        public static void ProxySteerable(ZSocket frontend, ZSocket backend, ZSocket capture, ZSocket control)
+        {
+            ZError error;
+            if (!ProxySteerable(frontend, backend, capture, control, out error))
+            {
+                if (error == ZError.ETERM)
+                {
+                    return; // Interrupted
+                }
+                throw new ZException(error);
+            }
+        }
+
+        public static bool ProxySteerable(ZSocket frontend, ZSocket backend, ZSocket capture, ZSocket control, out ZError error)
+        {
+            error = ZError.None;
+
+            while (-1 == zmq.proxy_steerable(frontend.SocketPtr, backend.SocketPtr, capture == null ? IntPtr.Zero : capture.SocketPtr, control == null ? IntPtr.Zero : control.SocketPtr))
+            {
+                error = ZError.GetLastErr();
+
+                if (error == ZError.EINTR)
+                {
+                    error = default(ZError);
+                    continue;
+                }
+                return false;
+            }
+            return true;
+        }
+
+        public void SetOption(ZContextOption option, int optionValue)
+        {
+            EnsureNotDisposed();
+
+            int rc = zmq.ctx_set(_contextPtr, (Int32)option, optionValue);
+            if (rc == -1)
+            {
+                var error = ZError.GetLastErr();
+
+                if (error == ZError.EINVAL)
+                {
+                    throw new ArgumentOutOfRangeException(
+                        string.Format("The requested option optionName \"{0}\" is invalid.", option));
+                }
+                throw new ZException(error);
+            }
+        }
+
+        public int GetOption(ZContextOption option)
+        {
+            EnsureNotDisposed();
+
+            int rc = zmq.ctx_get(_contextPtr, (Int32)option);
+            if (rc == -1)
+            {
+                var error = ZError.GetLastErr();
+
+                if (error == ZError.EINVAL)
+                {
+                    throw new ArgumentOutOfRangeException(
+                        string.Format("The requested option optionName \"{0}\" is invalid.", option));
+                }
+                throw new ZException(error);
+            }
+            return rc;
+        }
+
+        /// <summary>
+        /// Gets or sets the size of the thread pool for the current context (default = 1).
+        /// </summary>
+        public int ThreadPoolSize
+        {
+            get { return GetOption(ZContextOption.IO_THREADS); }
+            set { SetOption(ZContextOption.IO_THREADS, value); }
+        }
+
+        /// <summary>
+        /// Gets or sets the maximum number of sockets for the current context (default = 1024).
+        /// </summary>
+        public int MaxSockets
+        {
+            get { return GetOption(ZContextOption.MAX_SOCKETS); }
+            set { SetOption(ZContextOption.MAX_SOCKETS, value); }
+        }
+
+        /// <summary>
+        /// Gets or sets the supported socket protocol(s) when using TCP transports. (Default = <see cref="ProtocolType.Ipv4Only"/>).
+        /// </summary>
+        public bool IPv6Enabled
+        {
+            get { return GetOption(ZContextOption.IPV6) == 1; }
+            set { SetOption(ZContextOption.IPV6, value ? 1 : 0); }
+        }
+
+        /// <summary>
+        /// Shutdown the ZeroMQ context.
+        /// </summary>
+        public void Shutdown()
+        {
+            ZError error;
+            if (!Shutdown(out error))
+            {
+                throw new ZException(error);
+            }
+        }
+
+        /// <summary>
+        /// Shutdown the ZeroMQ context.
+        /// </summary>
+        public bool Shutdown(out ZError error)
+        {
+            error = default(ZError);
+
+            if (_contextPtr == IntPtr.Zero)
+                return true;
+
+            while (-1 == zmq.ctx_shutdown(_contextPtr))
+            {
+                error = ZError.GetLastErr();
+
+                if (error == ZError.EINTR)
+                {
+                    error = default(ZError);
+                    continue;
+                }
+
+                // Maybe ZError.EFAULT
+
+                return false;
+            }
+
+            // don't _contextPtr = IntPtr.Zero;
+            return true;
+        }
+
+        /// <summary>
+        /// Terminate the ZeroMQ context.
+        /// </summary>
+        public void Terminate()
+        {
+            ZError error;
+            if (!Terminate(out error))
+            {
+                throw new ZException(error);
+            }
+        }
+
+        /// <summary>
+        /// Terminate the ZeroMQ context.
+        /// </summary>
+        public bool Terminate(out ZError error)
+        {
+            error = ZError.None;
+            if (_contextPtr == IntPtr.Zero)
+                return true;
+
+            while (-1 == zmq.ctx_term(_contextPtr))
+            {
+                error = ZError.GetLastErr();
+
+                if (error == ZError.EINTR)
+                {
+                    error = default(ZError);
+                    continue;
+                }
+
+                // Maybe ZError.EFAULT
+
+                return false;
+            }
+
+            _contextPtr = IntPtr.Zero;
+            return true;
+        }
+
+        public void Dispose()
+        {
+            GC.SuppressFinalize(this);
+            Dispose(true);
+        }
+
+        void Dispose(bool disposing)
+        {
+            if (disposing)
+            {
+                ZError error;
+                Terminate(out error);
+            }
+        }
+
+        private void EnsureNotDisposed()
+        {
+            if (_contextPtr == IntPtr.Zero)
+            {
+                throw new ObjectDisposedException(GetType().FullName);
+            }
+        }
+    }
 }

برخی فایل ها در این مقایسه diff نمایش داده نمی شوند زیرا تعداد فایل ها بسیار زیاد است