From 890c2fce65d070ae7ba834e765013d12c479e558 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=A5=E6=B1=9D=E6=A3=8B=E8=8C=97?= <505554090@qq.com> Date: Sun, 3 Mar 2024 19:18:05 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/Adapter/AdapterConsoleApp/Program.cs | 8 +- .../AdapterTesterConsoleApp/Program.cs | 1 - .../CustomAdapterConsoleApp/Program.cs | 21 +- .../CustomFixedHeaderConsoleApp/Program.cs | 9 +- .../PackageAdapterConsoleApp/Program.cs | 10 +- .../BlogsDemos/HeartbeatConsoleApp/Program.cs | 3 +- .../ServiceConsoleApp/Program.cs | 24 +- examples/Core/AppMessengerWinApp/Form2.cs | 15 +- examples/Core/BytePoolConsoleApp/Program.cs | 30 +- .../Core/IocConsoleApp/NormalContainer.cs | 22 +- examples/Core/IocConsoleApp/Program.cs | 11 +- .../IocConsoleApp/SourceGeneratorContainer.cs | 43 +- examples/Core/PluginConsoleApp/Program.cs | 6 +- .../Dmtp/CustomDmtpActorConsoleApp/Program.cs | 11 +- .../Actor/ISimpleDmtpRpcActor.cs | 12 +- .../SimpleDmtpRpc/Actor/SimpleDmtpRpcActor.cs | 16 +- .../SimpleDmtpRpc/Common/MethodModel.cs | 11 +- .../Common/SimpleDmtpRpcPackage.cs | 12 +- .../Extensions/SimpleDmtpRpcExtension.cs | 13 +- .../SimpleDmtpRpc/SimpleDmtpRpcFeature.cs | 18 +- .../DispatchProxyDmtpRpcConsoleApp/Program.cs | 12 +- .../Dmtp/DmtpAspnetcoreConsoleApp/Program.cs | 4 +- .../Dmtp/DmtpChannelConsoleApp/Program.cs | 15 +- examples/Dmtp/DmtpConsoleApp/Program.cs | 26 +- examples/Dmtp/DmtpRedisConsoleApp/Program.cs | 2 +- examples/Dmtp/DmtpRpcClientApp/Form1.cs | 2 - examples/Dmtp/DmtpRpcClientApp/Program.cs | 4 +- examples/Dmtp/DmtpRpcClientApp/RpcProxy.cs | 642 ++++++------ .../Dmtp/DmtpRpcClientConsoleApp/Program.cs | 32 +- .../Dmtp/DmtpRpcServerConsoleApp/Program.cs | 8 +- .../Dmtp/DmtpRpcServerConsoleApp/RpcProxy.cs | 547 ++++++----- examples/Dmtp/DmtpWebApplication/Program.cs | 6 +- .../Dmtp/FileTransferConsoleApp/Program.cs | 30 +- .../Dmtp/NamedPipeDmtpConsoleApp/Program.cs | 8 +- .../RealityProxyDmtpRpcConsoleApp/Program.cs | 12 +- .../Dmtp/RecommendRpcConsoleApp/Program.cs | 3 +- .../Dmtp/RemoteStreamConsoleApp/Program.cs | 1 - .../Dmtp/RouterPackageConsoleApp/Program.cs | 15 +- .../AssemblyInfo.cs | 2 +- .../UserServer.cs | 1 - .../Hosting/HostingWorkerService/Program.cs | 8 +- .../Properties/launchSettings.json | 2 +- .../appsettings.Development.json | 2 +- .../HostingWorkerService/appsettings.json | 2 +- examples/Http/HttpClientConsoleApp/Program.cs | 5 +- .../Http/HttpServiceConsoleApp/Program.cs | 2 +- .../HttpServiceConsoleApp/api/css/index.css | 366 +++---- .../Http/HttpServiceConsoleApp/api/index.html | 3 - .../HttpServiceForCorsConsoleApp/Program.cs | 4 +- .../Program.cs | 11 +- .../JsonRpcClientConsoleApp/Program.cs | 3 +- .../JsonRpc/JsonRpcConsoleApp/JsonRpcProxy.cs | 555 ++++++----- examples/JsonRpc/JsonRpcConsoleApp/Program.cs | 8 +- .../ReverseJsonRpcConsoleApp/Program.cs | 18 +- .../Modbus/ModbusMasterConsoleApp/Program.cs | 7 +- .../Modbus/ModbusObjectConsoleApp/Program.cs | 26 +- .../Modbus/ModbusSlaveConsoleApp/Program.cs | 16 +- .../NamedPipeClientConsoleApp/Program.cs | 6 +- .../NamedPipeServiceConsoleApp/Program.cs | 14 +- .../Program.cs | 12 +- .../Program.cs | 7 +- .../Rpc/RpcRateLimitingConsoleApp/Program.cs | 7 +- .../SerialPortClientConsoleApp/Program.cs | 12 +- .../ReuseAddressServerConsoleApp/Program.cs | 7 +- .../Tcp/TcpCommandLineConsoleApp/Program.cs | 2 +- examples/Tcp/TcpConsoleApp/Program.cs | 26 +- .../Tcp/TcpWaitingClientWinFormsApp/Form1.cs | 2 +- .../TcpWaitingClientWinFormsApp/Program.cs | 7 +- .../Udp/UdpBroadcastConsoleApp/Program.cs | 6 +- examples/Udp/UdpDemoApp/Form1.cs | 2 +- .../ScreenUdpReceiver/Form1.cs | 2 +- .../UdpScreenCapture/ScreenUdpSender/Form1.cs | 2 +- .../Unity3d/UnityServerConsoleApp/Program.cs | 2 - .../UnityServerConsoleApp/UnityRpcProxy.cs | 317 +++--- .../DispatchProxyWebApiConsoleApp/Program.cs | 14 +- examples/WebApi/WebApiClientApp/Program.cs | 3 +- examples/WebApi/WebApiServer/Program.cs | 10 +- examples/WebApi/WebApiServer/WebApiProxy.cs | 928 +++++++++--------- .../AsyncWebSocketConsoleApp/Program.cs | 62 +- .../WebSocket/WebSocketConsoleApp/Program.cs | 58 +- .../Program.cs | 16 +- examples/XmlRpc/XmlRpcServerApp/Program.cs | 3 +- examples/XmlRpc/XmlRpcServerApp/RpcProxy.cs | 306 +++--- handbook/docs/websocketclient.mdx | 93 +- handbook/docs/websocketservice.mdx | 123 ++- 85 files changed, 2385 insertions(+), 2370 deletions(-) diff --git a/examples/Adapter/AdapterConsoleApp/Program.cs b/examples/Adapter/AdapterConsoleApp/Program.cs index 1f1745f97..0148d0579 100644 --- a/examples/Adapter/AdapterConsoleApp/Program.cs +++ b/examples/Adapter/AdapterConsoleApp/Program.cs @@ -143,7 +143,7 @@ namespace AdapterConsoleApp { //使用拼接模式发送,在发送流式数据之前 - int dataLen = 0; + var dataLen = 0; foreach (var item in transferBytes) { dataLen += item.Count; @@ -238,7 +238,7 @@ namespace AdapterConsoleApp } } - class MyClass : IRequestInfo + internal class MyClass : IRequestInfo { public OrderType OrderType { get; set; } public DataType DataType { get; set; } @@ -246,13 +246,13 @@ namespace AdapterConsoleApp public byte[] Data { get; set; } } - enum DataType : byte + internal enum DataType : byte { Down = 0, Up = 1 } - enum OrderType : byte + internal enum OrderType : byte { Hold = 0, Go = 1 diff --git a/examples/Adapter/AdapterTesterConsoleApp/Program.cs b/examples/Adapter/AdapterTesterConsoleApp/Program.cs index d7dd8c1a1..1134634e2 100644 --- a/examples/Adapter/AdapterTesterConsoleApp/Program.cs +++ b/examples/Adapter/AdapterTesterConsoleApp/Program.cs @@ -1,5 +1,4 @@ using TouchSocket.Core; -using TouchSocket.Sockets; namespace AdapterTesterConsoleApp { diff --git a/examples/Adapter/CustomAdapterConsoleApp/Program.cs b/examples/Adapter/CustomAdapterConsoleApp/Program.cs index 7e65d7d3f..5f8f9177d 100644 --- a/examples/Adapter/CustomAdapterConsoleApp/Program.cs +++ b/examples/Adapter/CustomAdapterConsoleApp/Program.cs @@ -6,7 +6,7 @@ namespace CustomAdapterConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var service = CreateService(); var client = CreateClient(); @@ -27,7 +27,7 @@ namespace CustomAdapterConsoleApp //构建发送数据 using (var byteBlock = new ByteBlock(1024)) { - byteBlock.Write((byte)(myRequestInfo.Body.Length+2));//先写长度,因为该长度还包含数据类型和指令类型,所以+2 + byteBlock.Write((byte)(myRequestInfo.Body.Length + 2));//先写长度,因为该长度还包含数据类型和指令类型,所以+2 byteBlock.Write((byte)myRequestInfo.DataType);//然后数据类型 byteBlock.Write((byte)myRequestInfo.OrderType);//然后指令类型 byteBlock.Write(myRequestInfo.Body);//再写数据 @@ -37,7 +37,7 @@ namespace CustomAdapterConsoleApp } } - static TcpClient CreateClient() + private static TcpClient CreateClient() { var client = new TcpClient(); //载入配置 @@ -54,7 +54,7 @@ namespace CustomAdapterConsoleApp return client; } - static TcpService CreateService() + private static TcpService CreateService() { var service = new TcpService(); service.Received = (client, e) => @@ -79,7 +79,7 @@ namespace CustomAdapterConsoleApp { //a.Add();//此处可以添加插件 })); - service.Start();//启动 + service.Start();//启动 service.Logger.Info("服务器已启动"); return service; } @@ -87,7 +87,6 @@ namespace CustomAdapterConsoleApp internal class MyCustomDataHandlingAdapter : CustomDataHandlingAdapter { - /// /// 筛选解析数据。实例化的TRequest会一直保存,直至解析成功,或手动清除。 /// 当不满足解析条件时,请返回,此时会保存的数据 @@ -108,18 +107,18 @@ namespace CustomAdapterConsoleApp return FilterResult.Cache;//当头部都无法解析时,直接缓存 } - int pos = byteBlock.Pos;//记录初始游标位置,防止本次无法解析时,回退游标。 + var pos = byteBlock.Pos;//记录初始游标位置,防止本次无法解析时,回退游标。 - MyRequestInfo myRequestInfo = new MyRequestInfo(); + var myRequestInfo = new MyRequestInfo(); //此操作实际上有两个作用, //1.填充header //2.将byteBlock.Pos递增3的长度。 - byteBlock.Read(out byte[] header, 3);//填充header + byteBlock.Read(out var header, 3);//填充header //因为第一个字节表示所有长度,而DataType、OrderType已经包含在了header里面。 //所有只需呀再读取header[0]-2个长度即可。 - byte bodyLength = (byte)(header[0] - 2); + var bodyLength = (byte)(header[0] - 2); if (bodyLength > byteBlock.CanReadLen) { @@ -132,7 +131,7 @@ namespace CustomAdapterConsoleApp //此操作实际上有两个作用, //1.填充body //2.将byteBlock.Pos递增bodyLength的长度。 - byteBlock.Read(out byte[] body, bodyLength); + byteBlock.Read(out var body, bodyLength); myRequestInfo.DataType = header[1]; myRequestInfo.OrderType = header[2]; diff --git a/examples/Adapter/CustomFixedHeaderConsoleApp/Program.cs b/examples/Adapter/CustomFixedHeaderConsoleApp/Program.cs index a961e8cbf..4b24020ce 100644 --- a/examples/Adapter/CustomFixedHeaderConsoleApp/Program.cs +++ b/examples/Adapter/CustomFixedHeaderConsoleApp/Program.cs @@ -6,7 +6,7 @@ namespace CustomFixedHeaderConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var service = CreateService(); var client = CreateClient(); @@ -37,7 +37,7 @@ namespace CustomFixedHeaderConsoleApp } } - static TcpClient CreateClient() + private static TcpClient CreateClient() { var client = new TcpClient(); //载入配置 @@ -54,7 +54,7 @@ namespace CustomFixedHeaderConsoleApp return client; } - static TcpService CreateService() + private static TcpService CreateService() { var service = new TcpService(); service.Received = (client, e) => @@ -124,7 +124,6 @@ namespace CustomFixedHeaderConsoleApp /// public byte[] Body { get; set; } - public bool OnParsingBody(byte[] body) { if (body.Length == this.BodyLength) @@ -135,7 +134,6 @@ namespace CustomFixedHeaderConsoleApp return false; } - public bool OnParsingHeader(byte[] header) { //在该示例中,第一个字节表示后续的所有数据长度,但是header设置的是3,所以后续还应当接收length-2个长度。 @@ -145,5 +143,4 @@ namespace CustomFixedHeaderConsoleApp return true; } } - } \ No newline at end of file diff --git a/examples/Adapter/PackageAdapterConsoleApp/Program.cs b/examples/Adapter/PackageAdapterConsoleApp/Program.cs index 7093d3ee9..50fc4049b 100644 --- a/examples/Adapter/PackageAdapterConsoleApp/Program.cs +++ b/examples/Adapter/PackageAdapterConsoleApp/Program.cs @@ -6,7 +6,7 @@ namespace PackageAdapterConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var service = CreateService(); var client = CreateClient(); @@ -22,13 +22,13 @@ namespace PackageAdapterConsoleApp } } - static SingleStreamDataHandlingAdapter GetAdapter() + private static SingleStreamDataHandlingAdapter GetAdapter() { return new TerminatorPackageAdapter("\r\n");//使用换行终止字符 //return new PeriodPackageAdapter() { CacheTimeout=TimeSpan.FromMilliseconds(100) };//使用周期适配器。 } - static TcpClient CreateClient() + private static TcpClient CreateClient() { var client = new TcpClient(); //载入配置 @@ -45,13 +45,13 @@ namespace PackageAdapterConsoleApp return client; } - static TcpService CreateService() + private static TcpService CreateService() { var service = new TcpService(); service.Received = (client, e) => { //从客户端收到信息 - string mes = Encoding.UTF8.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);//注意:数据长度是byteBlock.Len + var mes = Encoding.UTF8.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);//注意:数据长度是byteBlock.Len client.Logger.Info($"已从{client.Id}接收到信息:{mes}"); return EasyTask.CompletedTask; }; diff --git a/examples/BlogsDemos/HeartbeatConsoleApp/Program.cs b/examples/BlogsDemos/HeartbeatConsoleApp/Program.cs index 8f0d71568..a20c10483 100644 --- a/examples/BlogsDemos/HeartbeatConsoleApp/Program.cs +++ b/examples/BlogsDemos/HeartbeatConsoleApp/Program.cs @@ -201,13 +201,12 @@ namespace HeartbeatConsoleApp private readonly ILog logger; [DependencyInject] - public HeartbeatAndReceivePlugin( ILog logger,int timeTick= 1000 * 5) + public HeartbeatAndReceivePlugin(ILog logger, int timeTick = 1000 * 5) { this.m_timeTick = timeTick; this.logger = logger; } - public async Task OnTcpConnected(ITcpClientBase client, ConnectedEventArgs e) { if (client is ISocketClient) diff --git a/examples/Consul集群示例/TouchRpc Consul集群/ServiceConsoleApp/Program.cs b/examples/Consul集群示例/TouchRpc Consul集群/ServiceConsoleApp/Program.cs index 247840ba8..06e2bc4cc 100644 --- a/examples/Consul集群示例/TouchRpc Consul集群/ServiceConsoleApp/Program.cs +++ b/examples/Consul集群示例/TouchRpc Consul集群/ServiceConsoleApp/Program.cs @@ -137,21 +137,29 @@ namespace ServiceConsoleApp /// /// WS收到数据等业务。 /// - internal class MyWebSocketPlug : PluginBase, IWebSocketHandshakedPlugin, IWebSocketReceivedPlugin + internal class MyWebSocketPlug : PluginBase, IWebSocketHandshakedPlugin, IWebSocketReceivedPlugin { - public Task OnWebSocketHandshaked(IHttpSocketClient client, HttpContextEventArgs e) + public async Task OnWebSocketHandshaked(IWebSocket client, HttpContextEventArgs e) { - client.Logger.Info($"WS客户端连接,ID={client.Id},IPHost={client.IP}:{client.Port}"); - return Task.CompletedTask; + if (client.Client is IHttpSocketClient socketClient) + { + socketClient.Logger.Info($"WS客户端连接,ID={socketClient.Id},IPHost={socketClient.IP}:{socketClient.Port}"); + } + + await e.InvokeNext(); } - public Task OnWebSocketReceived(IHttpSocketClient client, WSDataFrameEventArgs e) + public async Task OnWebSocketReceived(IWebSocket client, WSDataFrameEventArgs e) { - if (e.DataFrame.Opcode == WSDataType.Text) + if (client.Client is IHttpSocketClient socketClient) { - client.Logger.Info($"WS Msg={e.DataFrame.ToText()}"); + if (e.DataFrame.Opcode == WSDataType.Text) + { + socketClient.Logger.Info($"WS Msg={e.DataFrame.ToText()}"); + } } - return Task.CompletedTask; + + await e.InvokeNext(); } } } \ No newline at end of file diff --git a/examples/Core/AppMessengerWinApp/Form2.cs b/examples/Core/AppMessengerWinApp/Form2.cs index bcbef286e..deb5251e2 100644 --- a/examples/Core/AppMessengerWinApp/Form2.cs +++ b/examples/Core/AppMessengerWinApp/Form2.cs @@ -1,13 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; -using TouchSocket.Core; +using TouchSocket.Core; namespace AppMessengerWinApp { @@ -15,7 +6,7 @@ namespace AppMessengerWinApp { public Form2() { - InitializeComponent(); + this.InitializeComponent(); } [AppMessage] @@ -25,4 +16,4 @@ namespace AppMessengerWinApp this.listBox1.Items.Add(msg); } } -} +} \ No newline at end of file diff --git a/examples/Core/BytePoolConsoleApp/Program.cs b/examples/Core/BytePoolConsoleApp/Program.cs index 344542d82..91e3ddc09 100644 --- a/examples/Core/BytePoolConsoleApp/Program.cs +++ b/examples/Core/BytePoolConsoleApp/Program.cs @@ -18,7 +18,7 @@ namespace BytePoolConsoleApp Console.ReadKey(); } - static void IPackageWriteRead() + private static void IPackageWriteRead() { using (var byteBlock = new ByteBlock()) { @@ -32,7 +32,7 @@ namespace BytePoolConsoleApp } } - static void BytesPackageWriteRead() + private static void BytesPackageWriteRead() { using (var byteBlock = new ByteBlock()) { @@ -40,19 +40,19 @@ namespace BytePoolConsoleApp byteBlock.SeekToStart(); - byte[] bytes = byteBlock.ReadBytesPackage(); + var bytes = byteBlock.ReadBytesPackage(); byteBlock.SeekToStart(); //使用下列方式即可高效完成读取 - if (byteBlock.TryReadBytesPackageInfo(out int pos, out int len)) + if (byteBlock.TryReadBytesPackageInfo(out var pos, out var len)) { var str = Encoding.UTF8.GetString(byteBlock.Buffer, pos, len); } } } - static void ObjectWriteRead() + private static void ObjectWriteRead() { using (var byteBlock = new ByteBlock()) { @@ -66,7 +66,7 @@ namespace BytePoolConsoleApp } } - static void PrimitiveWriteRead() + private static void PrimitiveWriteRead() { using (var byteBlock = new ByteBlock()) { @@ -77,14 +77,14 @@ namespace BytePoolConsoleApp byteBlock.SeekToStart();//读取时,先将游标移动到初始写入的位置,然后按写入顺序,依次读取 - byte byteValue = (byte)byteBlock.ReadByte(); - int intValue = byteBlock.ReadInt32(); - long longValue = byteBlock.ReadInt64(); - string stringValue = byteBlock.ReadString(); + var byteValue = (byte)byteBlock.ReadByte(); + var intValue = byteBlock.ReadInt32(); + var longValue = byteBlock.ReadInt64(); + var stringValue = byteBlock.ReadString(); } } - static void BaseWriteRead() + private static void BaseWriteRead() { using (var byteBlock = new ByteBlock()) { @@ -97,9 +97,9 @@ namespace BytePoolConsoleApp } } - static void NewBytePool() + private static void NewBytePool() { - BytePool bytePool = new BytePool(maxArrayLength: 1024 * 1024, maxArraysPerBucket: 50) + var bytePool = new BytePool(maxArrayLength: 1024 * 1024, maxArraysPerBucket: 50) { AutoZero = false,//在回收内存时,是否清空内存 MaxBucketsToTry = 5//最大梯度跨度 @@ -133,7 +133,7 @@ namespace BytePoolConsoleApp } } - class MyPackage : PackageBase + internal class MyPackage : PackageBase { public int Property { get; set; } @@ -148,7 +148,7 @@ namespace BytePoolConsoleApp } } - class MyClass + internal class MyClass { public int Property { get; set; } } diff --git a/examples/Core/IocConsoleApp/NormalContainer.cs b/examples/Core/IocConsoleApp/NormalContainer.cs index 064aeb814..7f7b9699e 100644 --- a/examples/Core/IocConsoleApp/NormalContainer.cs +++ b/examples/Core/IocConsoleApp/NormalContainer.cs @@ -14,10 +14,11 @@ namespace IocConsoleApp PropertyInject(); MethodInject(); } + /// /// 构造函数注入 /// - static void ConstructorInject() + private static void ConstructorInject() { var container = GetContainer(); container.RegisterSingleton(); @@ -32,7 +33,7 @@ namespace IocConsoleApp /// /// 属性注入 /// - static void PropertyInject() + private static void PropertyInject() { var container = GetContainer(); container.RegisterSingleton(); @@ -48,7 +49,7 @@ namespace IocConsoleApp /// /// 方法注入 /// - static void MethodInject() + private static void MethodInject() { var container = GetContainer(); container.RegisterSingleton(); @@ -58,8 +59,7 @@ namespace IocConsoleApp Console.WriteLine(MethodBase.GetCurrentMethod().Name); } - - static IContainer GetContainer() + private static IContainer GetContainer() { return new Container();//默认IOC容器 @@ -67,12 +67,11 @@ namespace IocConsoleApp } } - class MyClass1 + internal class MyClass1 { - } - class MyClass2 + internal class MyClass2 { public MyClass2(MyClass1 myClass1) { @@ -82,7 +81,7 @@ namespace IocConsoleApp public MyClass1 MyClass1 { get; } } - class MyClass3 + internal class MyClass3 { /// /// 直接按类型,默认方式获取 @@ -103,15 +102,14 @@ namespace IocConsoleApp public MyClass1 KeyMyClass1 { get; set; } } - class MyClass4 + internal class MyClass4 { public MyClass1 MyClass1 { get; private set; } - [DependencyInject] public void MethodInject(MyClass1 myClass1) { this.MyClass1 = myClass1; } } -} +} \ No newline at end of file diff --git a/examples/Core/IocConsoleApp/Program.cs b/examples/Core/IocConsoleApp/Program.cs index be49f6dab..3a044b063 100644 --- a/examples/Core/IocConsoleApp/Program.cs +++ b/examples/Core/IocConsoleApp/Program.cs @@ -1,19 +1,12 @@ -using Microsoft.Extensions.DependencyInjection; -using System.Reflection; -using TouchSocket.Core; -using TouchSocket.Core.AspNetCore; - -namespace IocConsoleApp +namespace IocConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { NormalContainer.Run();// 常规Ioc容器,使用IL和反射实现,支持运行时注册和获取 SourceGeneratorContainer.Run();// 源生成Ioc容器,单例实例支持运行时注册和获取,其他模式只能在编码阶段自动生成。 Console.ReadKey(); } - - } } \ No newline at end of file diff --git a/examples/Core/IocConsoleApp/SourceGeneratorContainer.cs b/examples/Core/IocConsoleApp/SourceGeneratorContainer.cs index f5cec9074..06e0e3c1b 100644 --- a/examples/Core/IocConsoleApp/SourceGeneratorContainer.cs +++ b/examples/Core/IocConsoleApp/SourceGeneratorContainer.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using TouchSocket.Core; +using TouchSocket.Core; namespace IocConsoleApp { @@ -11,7 +6,7 @@ namespace IocConsoleApp { public static void Run() { - MyContainer container = new MyContainer(); + var container = new MyContainer(); var interface10 = container.Resolve(); var interface11 = container.Resolve(); } @@ -20,37 +15,33 @@ namespace IocConsoleApp [AddSingletonInject(typeof(IInterface10), typeof(MyClass10))]//直接添加现有类型为单例 [AddTransientInject(typeof(IInterface11), typeof(MyClass11))]//直接添加现有类型为瞬态 [GeneratorContainer] - partial class MyContainer : ManualContainer + internal partial class MyContainer : ManualContainer { - - } - interface IInterface10 - { - - } - class MyClass10 : IInterface10 - { - } - interface IInterface11 + internal interface IInterface10 { - } - class MyClass11 : IInterface11 - { + internal class MyClass10 : IInterface10 + { + } + + internal interface IInterface11 + { + } + + internal class MyClass11 : IInterface11 + { } [AutoInjectForSingleton]//将声明的类型直接标识为单例注入 - class MyClass12 + internal class MyClass12 { - } [AutoInjectForTransient]//将声明的类型直接标识为瞬态注入 - class MyClass13 + internal class MyClass13 { - } -} +} \ No newline at end of file diff --git a/examples/Core/PluginConsoleApp/Program.cs b/examples/Core/PluginConsoleApp/Program.cs index fad8cfa86..ec7ea345d 100644 --- a/examples/Core/PluginConsoleApp/Program.cs +++ b/examples/Core/PluginConsoleApp/Program.cs @@ -1,5 +1,5 @@ -using System.Threading.Tasks; -using System; +using System; +using System.Threading.Tasks; using TouchSocket.Core; namespace PluginConsoleApp @@ -39,7 +39,6 @@ namespace PluginConsoleApp Words = Console.ReadLine() }); } - } } @@ -102,6 +101,7 @@ namespace PluginConsoleApp Console.WriteLine($"{this.GetType().Name}------Leave"); } } + internal class LastSayPlugin : PluginBase, ISayPlugin { public async Task Say(object sender, MyPluginEventArgs e) diff --git a/examples/Dmtp/CustomDmtpActorConsoleApp/Program.cs b/examples/Dmtp/CustomDmtpActorConsoleApp/Program.cs index 28c9aa1cb..267980d15 100644 --- a/examples/Dmtp/CustomDmtpActorConsoleApp/Program.cs +++ b/examples/Dmtp/CustomDmtpActorConsoleApp/Program.cs @@ -1,9 +1,6 @@ using CustomDmtpActorConsoleApp.SimpleDmtpRpc; -using System.Reflection; using TouchSocket.Core; using TouchSocket.Dmtp; -using TouchSocket.Dmtp.Rpc; -using TouchSocket.Resources; using TouchSocket.Sockets; namespace CustomDmtpActorConsoleApp @@ -13,14 +10,14 @@ namespace CustomDmtpActorConsoleApp /// internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var service = GetTcpDmtpService(); var client = GetTcpDmtpClient(); while (true) { - string methodName = Console.ReadLine(); + var methodName = Console.ReadLine(); var actor = client.GetSimpleDmtpRpcActor(); try @@ -88,15 +85,13 @@ namespace CustomDmtpActorConsoleApp service.Logger.Info("服务器成功启动"); return service; } - } - class MyServer + internal class MyServer { public void SayHello() { Console.WriteLine("Hello"); } } - } \ No newline at end of file diff --git a/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Actor/ISimpleDmtpRpcActor.cs b/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Actor/ISimpleDmtpRpcActor.cs index 2a7be1a1c..a0e56ae1e 100644 --- a/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Actor/ISimpleDmtpRpcActor.cs +++ b/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Actor/ISimpleDmtpRpcActor.cs @@ -1,15 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using TouchSocket.Dmtp; +using TouchSocket.Dmtp; namespace CustomDmtpActorConsoleApp.SimpleDmtpRpc { - interface ISimpleDmtpRpcActor : IActor + internal interface ISimpleDmtpRpcActor : IActor { void Invoke(string methodName); + void Invoke(string targetId, string methodName); } -} +} \ No newline at end of file diff --git a/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Actor/SimpleDmtpRpcActor.cs b/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Actor/SimpleDmtpRpcActor.cs index 22a6ce302..246fa6c78 100644 --- a/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Actor/SimpleDmtpRpcActor.cs +++ b/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Actor/SimpleDmtpRpcActor.cs @@ -1,16 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using TouchSocket.Core; +using TouchSocket.Core; using TouchSocket.Dmtp; -using TouchSocket.Dmtp.Rpc; -using TouchSocket.Rpc; namespace CustomDmtpActorConsoleApp.SimpleDmtpRpc { - class SimpleDmtpRpcActor : ISimpleDmtpRpcActor + internal class SimpleDmtpRpcActor : ISimpleDmtpRpcActor { private ushort m_invoke_Request = 1000; private ushort m_invoke_Response = 1001; @@ -160,6 +153,7 @@ namespace CustomDmtpActorConsoleApp.SimpleDmtpRpc { this.PrivateInvoke(default, methodName); } + public async void Invoke(string targetId, string methodName) { if (string.IsNullOrEmpty(targetId)) @@ -206,10 +200,12 @@ namespace CustomDmtpActorConsoleApp.SimpleDmtpRpc var result = (SimpleDmtpRpcPackage)waitData.WaitResult; result.CheckStatus(); return; + case WaitDataStatus.Overtime: throw new TimeoutException(); case WaitDataStatus.Canceled: break; + case WaitDataStatus.Default: case WaitDataStatus.Disposed: default: @@ -222,4 +218,4 @@ namespace CustomDmtpActorConsoleApp.SimpleDmtpRpc } } } -} +} \ No newline at end of file diff --git a/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Common/MethodModel.cs b/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Common/MethodModel.cs index 3944740c1..7171fee8a 100644 --- a/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Common/MethodModel.cs +++ b/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Common/MethodModel.cs @@ -1,13 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; +using System.Reflection; namespace CustomDmtpActorConsoleApp.SimpleDmtpRpc { - class MethodModel + internal class MethodModel { public MethodModel(MethodInfo method, object target) { @@ -18,4 +13,4 @@ namespace CustomDmtpActorConsoleApp.SimpleDmtpRpc public MethodInfo Method { get; private set; } public object Target { get; private set; } } -} +} \ No newline at end of file diff --git a/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Common/SimpleDmtpRpcPackage.cs b/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Common/SimpleDmtpRpcPackage.cs index 7d320fb3b..04c88d9b4 100644 --- a/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Common/SimpleDmtpRpcPackage.cs +++ b/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Common/SimpleDmtpRpcPackage.cs @@ -1,13 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using TouchSocket.Core; +using TouchSocket.Core; namespace CustomDmtpActorConsoleApp.SimpleDmtpRpc { - class SimpleDmtpRpcPackage : WaitRouterPackage + internal class SimpleDmtpRpcPackage : WaitRouterPackage { protected override bool IncludedRouter => true; @@ -39,5 +34,4 @@ namespace CustomDmtpActorConsoleApp.SimpleDmtpRpc } } } - -} +} \ No newline at end of file diff --git a/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Extensions/SimpleDmtpRpcExtension.cs b/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Extensions/SimpleDmtpRpcExtension.cs index 4dc3bc768..7acd3a641 100644 --- a/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Extensions/SimpleDmtpRpcExtension.cs +++ b/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/Extensions/SimpleDmtpRpcExtension.cs @@ -1,14 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using TouchSocket.Core; +using TouchSocket.Core; using TouchSocket.Dmtp; namespace CustomDmtpActorConsoleApp.SimpleDmtpRpc { - static class SimpleDmtpRpcExtension + internal static class SimpleDmtpRpcExtension { #region DependencyProperty @@ -31,6 +26,7 @@ namespace CustomDmtpActorConsoleApp.SimpleDmtpRpc { return pluginManager.Add(); } + #endregion 插件扩展 /// @@ -69,5 +65,4 @@ namespace CustomDmtpActorConsoleApp.SimpleDmtpRpc smtpActor.SetValue(SimpleDmtpRpcActorProperty, smtpRpcActor); } } - -} +} \ No newline at end of file diff --git a/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/SimpleDmtpRpcFeature.cs b/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/SimpleDmtpRpcFeature.cs index c7933bae6..88f560551 100644 --- a/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/SimpleDmtpRpcFeature.cs +++ b/examples/Dmtp/CustomDmtpActorConsoleApp/SimpleDmtpRpc/SimpleDmtpRpcFeature.cs @@ -1,18 +1,13 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; +using System.Reflection; using TouchSocket.Core; using TouchSocket.Dmtp; -using TouchSocket.Dmtp.Rpc; namespace CustomDmtpActorConsoleApp.SimpleDmtpRpc { - class SimpleDmtpRpcFeature : PluginBase, IDmtpHandshakingPlugin, IDmtpReceivedPlugin + internal class SimpleDmtpRpcFeature : PluginBase, IDmtpHandshakingPlugin, IDmtpReceivedPlugin { - readonly Dictionary m_pairs = new Dictionary(); + private readonly Dictionary m_pairs = new Dictionary(); + public async Task OnDmtpHandshaking(IDmtpActorObject client, DmtpVerifyEventArgs e) { var actor = new SimpleDmtpRpcActor(client.DmtpActor) @@ -41,7 +36,7 @@ namespace CustomDmtpActorConsoleApp.SimpleDmtpRpc foreach (var item in server.GetType().GetMethods(BindingFlags.Default | BindingFlags.Instance | BindingFlags.Public)) { - m_pairs.Add(item.Name, new MethodModel(item, server)); + this.m_pairs.Add(item.Name, new MethodModel(item, server)); } } @@ -58,5 +53,4 @@ namespace CustomDmtpActorConsoleApp.SimpleDmtpRpc await e.InvokeNext(); } } - -} +} \ No newline at end of file diff --git a/examples/Dmtp/DispatchProxyDmtpRpcConsoleApp/Program.cs b/examples/Dmtp/DispatchProxyDmtpRpcConsoleApp/Program.cs index 1826ccda9..ead833856 100644 --- a/examples/Dmtp/DispatchProxyDmtpRpcConsoleApp/Program.cs +++ b/examples/Dmtp/DispatchProxyDmtpRpcConsoleApp/Program.cs @@ -1,8 +1,6 @@ -using System.ComponentModel; -using TouchSocket.Core; +using TouchSocket.Core; using TouchSocket.Dmtp; using TouchSocket.Dmtp.Rpc; -using TouchSocket.Rpc; using TouchSocket.Sockets; namespace DispatchProxyDmtpRpcConsoleApp @@ -13,7 +11,7 @@ namespace DispatchProxyDmtpRpcConsoleApp /// 调用前先启动DmtpRpcServerConsoleApp项目 /// /// - static void Main(string[] args) + private static void Main(string[] args) { var myRpcServer = DmtpRpcDispatchProxy.Create(); @@ -26,7 +24,7 @@ namespace DispatchProxyDmtpRpcConsoleApp /// 新建一个类,按照需要,继承DmtpRpcDispatchProxy,亦或者预设的JsonRpcDispatchProxy,亦或者RpcDispatchProxy基类。 /// 然后实现抽象方法,主要是能获取到调用的IRpcClient派生接口。 /// - class MyDmtpRpcDispatchProxy : DmtpRpcDispatchProxy + private class MyDmtpRpcDispatchProxy : DmtpRpcDispatchProxy { private readonly TcpDmtpClient m_client; @@ -59,11 +57,11 @@ namespace DispatchProxyDmtpRpcConsoleApp public override IDmtpRpcActor GetClient() { - return m_client.GetDmtpRpcActor(); + return this.m_client.GetDmtpRpcActor(); } } - interface IMyRpcServer + private interface IMyRpcServer { /// /// 将两个数相加 diff --git a/examples/Dmtp/DmtpAspnetcoreConsoleApp/Program.cs b/examples/Dmtp/DmtpAspnetcoreConsoleApp/Program.cs index 2179b0527..d0e2c2312 100644 --- a/examples/Dmtp/DmtpAspnetcoreConsoleApp/Program.cs +++ b/examples/Dmtp/DmtpAspnetcoreConsoleApp/Program.cs @@ -6,7 +6,7 @@ namespace DmtpAspnetcoreConsoleApp { internal class Program { - static async Task Main(string[] args) + private static async Task Main(string[] args) { //WebSocketDmtpClient连接 var websocketDmtpClient = new WebSocketDmtpClient(); @@ -33,4 +33,4 @@ namespace DmtpAspnetcoreConsoleApp Console.ReadKey(); } } -} +} \ No newline at end of file diff --git a/examples/Dmtp/DmtpChannelConsoleApp/Program.cs b/examples/Dmtp/DmtpChannelConsoleApp/Program.cs index 5ec075a02..64f1f3bda 100644 --- a/examples/Dmtp/DmtpChannelConsoleApp/Program.cs +++ b/examples/Dmtp/DmtpChannelConsoleApp/Program.cs @@ -6,23 +6,22 @@ namespace DmtpChannelConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var service = GetTcpDmtpService(); var client = GetTcpDmtpClient(); var consoleAction = new ConsoleAction(); - consoleAction.Add("1","测试完成写入", () => { RunComplete(client); }); - consoleAction.Add("2","测试Hold", () => { RunHoldOn(client); }); - + consoleAction.Add("1", "测试完成写入", () => { RunComplete(client); }); + consoleAction.Add("2", "测试Hold", () => { RunHoldOn(client); }); consoleAction.ShowAll(); consoleAction.RunCommandLine(); } - static void RunHoldOn(IDmtpActorObject client) + private static void RunHoldOn(IDmtpActorObject client) { //HoldOn的使用,主要是解决同一个通道中,多个数据流传输的情况。 @@ -37,7 +36,7 @@ namespace DmtpChannelConsoleApp for (var i = 0; i < 100; i++)//循环100次 { - for (int j = 0; j < 10; j++) + for (var j = 0; j < 10; j++) { //2.持续写入数据 channel.Write(bytes); @@ -52,7 +51,7 @@ namespace DmtpChannelConsoleApp } } - static void RunComplete(IDmtpActorObject client) + private static void RunComplete(IDmtpActorObject client) { var count = 1024 * 1;//测试1Gb数据 @@ -134,6 +133,7 @@ namespace DmtpChannelConsoleApp { this.m_logger = logger; } + public async Task OnCreateChannel(IDmtpActorObject client, CreateChannelEventArgs e) { if (client.TrySubscribeChannel(e.ChannelId, out var channel)) @@ -160,7 +160,6 @@ namespace DmtpChannelConsoleApp this.m_logger.Info($"通道接收结束,状态={channel.Status},短语={channel.LastOperationMes},共接收{count / (1048576.0):0.00}Mb字节"); } - } } diff --git a/examples/Dmtp/DmtpConsoleApp/Program.cs b/examples/Dmtp/DmtpConsoleApp/Program.cs index 3b938b534..e6c462e92 100644 --- a/examples/Dmtp/DmtpConsoleApp/Program.cs +++ b/examples/Dmtp/DmtpConsoleApp/Program.cs @@ -8,9 +8,9 @@ namespace DmtpConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { - ConsoleAction action = new ConsoleAction(); + var action = new ConsoleAction(); action.Add("1", "测试连接", Connect_1); action.Add("2", "测试以普通Tcp连接", Connect_2); action.Add("3", "发送消息", Send); @@ -27,7 +27,7 @@ namespace DmtpConsoleApp Console.WriteLine(obj.Message); } - static void Send() + private static void Send() { using var client = new TcpDmtpClient(); @@ -41,7 +41,7 @@ namespace DmtpConsoleApp //此处使用委托注册插件。和类插件功能一样 a.Add(nameof(IDmtpReceivedPlugin.OnDmtpReceived), async (object s, DmtpMessageEventArgs e) => { - string msg = e.DmtpMessage.BodyByteBlock.ToString(); + var msg = e.DmtpMessage.BodyByteBlock.ToString(); await Console.Out.WriteLineAsync($"收到服务器回信,协议{e.DmtpMessage.ProtocolFlags}收到信息,内容:{msg}"); await e.InvokeNext(); }); @@ -72,7 +72,7 @@ namespace DmtpConsoleApp /// 使用普通tcp连接 /// /// - static async void Connect_2() + private static async void Connect_2() { using var tcpClient = new TcpClient();//创建一个普通的tcp客户端。 tcpClient.Received = (client, e) => @@ -91,6 +91,7 @@ namespace DmtpConsoleApp }; #region 基础Flag协议 + Console.WriteLine($"{nameof(DmtpActor.P0_Close)}-flag-->{DmtpActor.P0_Close}"); Console.WriteLine($"{nameof(DmtpActor.P1_Handshake_Request)}-flag-->{DmtpActor.P1_Handshake_Request}"); Console.WriteLine($"{nameof(DmtpActor.P2_Handshake_Response)}-flag-->{DmtpActor.P2_Handshake_Response}"); @@ -101,10 +102,11 @@ namespace DmtpConsoleApp Console.WriteLine($"{nameof(DmtpActor.P7_CreateChannel_Request)}-flag-->{DmtpActor.P7_CreateChannel_Request}"); Console.WriteLine($"{nameof(DmtpActor.P8_CreateChannel_Response)}-flag-->{DmtpActor.P8_CreateChannel_Response}"); Console.WriteLine($"{nameof(DmtpActor.P9_ChannelPackage)}-flag-->{DmtpActor.P9_ChannelPackage}"); - #endregion + #endregion 基础Flag协议 #region 连接 + //开始链接服务器 tcpClient.Connect("127.0.0.1:7789"); @@ -127,7 +129,8 @@ namespace DmtpConsoleApp tcpClient.Send(byteBlock); } - #endregion + + #endregion 连接 #region Ping @@ -144,7 +147,8 @@ namespace DmtpConsoleApp tcpClient.Send(byteBlock); } - #endregion + + #endregion Ping await Task.Delay(2000); } @@ -155,7 +159,7 @@ namespace DmtpConsoleApp /// 2、设置Metadata,可以传递更多的验证信息。 /// 3、设置默认Id。 /// - static void Connect_1() + private static void Connect_1() { using var client = new TcpDmtpClient(); client.Setup(new TouchSocketConfig() @@ -177,7 +181,7 @@ namespace DmtpConsoleApp client.Logger.Info($"{nameof(Connect_1)}连接成功,Id={client.Id}"); } - static TcpDmtpService CreateTcpDmtpService() + private static TcpDmtpService CreateTcpDmtpService() { var service = new TcpDmtpService(); var config = new TouchSocketConfig()//配置 @@ -233,7 +237,7 @@ namespace DmtpConsoleApp if (e.DmtpMessage.ProtocolFlags == 1000) { //判断完协议以后,从 e.DmtpMessage.BodyByteBlock可以拿到实际的数据 - string msg = e.DmtpMessage.BodyByteBlock.ToString(); + var msg = e.DmtpMessage.BodyByteBlock.ToString(); await Console.Out.WriteLineAsync($"从协议{e.DmtpMessage.ProtocolFlags}收到信息,内容:{msg}"); //向客户端回发消息 diff --git a/examples/Dmtp/DmtpRedisConsoleApp/Program.cs b/examples/Dmtp/DmtpRedisConsoleApp/Program.cs index 1a599360d..acf147fbd 100644 --- a/examples/Dmtp/DmtpRedisConsoleApp/Program.cs +++ b/examples/Dmtp/DmtpRedisConsoleApp/Program.cs @@ -7,7 +7,7 @@ namespace DmtpRedisConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var service = GetTcpDmtpService(); var client = GetTcpDmtpClient(); diff --git a/examples/Dmtp/DmtpRpcClientApp/Form1.cs b/examples/Dmtp/DmtpRpcClientApp/Form1.cs index b59dd2927..439e34339 100644 --- a/examples/Dmtp/DmtpRpcClientApp/Form1.cs +++ b/examples/Dmtp/DmtpRpcClientApp/Form1.cs @@ -1,6 +1,5 @@ using RpcProxy; using System; -using System.Threading.Tasks; using System.Windows.Forms; using TouchSocket.Core; using TouchSocket.Dmtp; @@ -44,7 +43,6 @@ namespace DmtpClientApp private void Form1_Load(object sender, EventArgs e) { - } private void button4_Click(object sender, EventArgs e) diff --git a/examples/Dmtp/DmtpRpcClientApp/Program.cs b/examples/Dmtp/DmtpRpcClientApp/Program.cs index 4e846ac74..e5cf5bd37 100644 --- a/examples/Dmtp/DmtpRpcClientApp/Program.cs +++ b/examples/Dmtp/DmtpRpcClientApp/Program.cs @@ -32,7 +32,7 @@ namespace DmtpClientApp var service = new TcpDmtpService(); var config = new TouchSocketConfig()// .SetListenIPHosts(port) - .ConfigureContainer(a => + .ConfigureContainer(a => { a.AddRpcStore(store => { @@ -44,7 +44,7 @@ namespace DmtpClientApp }) .ConfigurePlugins(a => { - a.Add(nameof(IDmtpHandshakingPlugin.OnDmtpHandshaking), async (c,e) => + a.Add(nameof(IDmtpHandshakingPlugin.OnDmtpHandshaking), async (c, e) => { await e.InvokeNext(); }); diff --git a/examples/Dmtp/DmtpRpcClientApp/RpcProxy.cs b/examples/Dmtp/DmtpRpcClientApp/RpcProxy.cs index c95647fbf..142ee238e 100644 --- a/examples/Dmtp/DmtpRpcClientApp/RpcProxy.cs +++ b/examples/Dmtp/DmtpRpcClientApp/RpcProxy.cs @@ -2,334 +2,356 @@ 此代码由Rpc工具直接生成,非必要请不要修改此处代码 */ #pragma warning disable + using System; -using TouchSocket.Core; -using TouchSocket.Sockets; -using TouchSocket.Rpc; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading.Tasks; +using TouchSocket.Core; +using TouchSocket.Rpc; +using TouchSocket.Sockets; + namespace RpcProxy { -public interface IMyRpcServer:TouchSocket.Rpc.IRemoteServer -{ -/// -///登录 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -System.Boolean Login(System.String account,System.String password,IInvokeOption invokeOption = default); -/// -///登录 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task LoginAsync(System.String account,System.String password,IInvokeOption invokeOption = default); + public interface IMyRpcServer : TouchSocket.Rpc.IRemoteServer + { + /// + ///登录 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + System.Boolean Login(System.String account, System.String password, IInvokeOption invokeOption = default); -/// -///注册 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -System.Boolean Register(RegisterModel register,IInvokeOption invokeOption = default); -/// -///注册 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task RegisterAsync(RegisterModel register,IInvokeOption invokeOption = default); + /// + ///登录 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task LoginAsync(System.String account, System.String password, IInvokeOption invokeOption = default); -/// -///性能测试 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -System.Int32 Performance(System.Int32 a,IInvokeOption invokeOption = default); -/// -///性能测试 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task PerformanceAsync(System.Int32 a,IInvokeOption invokeOption = default); + /// + ///注册 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + System.Boolean Register(RegisterModel register, IInvokeOption invokeOption = default); -/// -///测试out -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -System.Boolean OutBytes(out System.Byte[] bytes,IInvokeOption invokeOption = default); -/// -///测试out -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task OutBytesAsync(out System.Byte[] bytes,IInvokeOption invokeOption = default); + /// + ///注册 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task RegisterAsync(RegisterModel register, IInvokeOption invokeOption = default); -} -public class MyRpcServer :IMyRpcServer -{ -public MyRpcServer(IRpcClient client) -{ -this.Client=client; -} -public IRpcClient Client{get;private set; } -/// -///登录 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public System.Boolean Login(System.String account,System.String password,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{account,password}; -System.Boolean returnData=(System.Boolean)Client.Invoke(typeof(System.Boolean),"Login",invokeOption, parameters); -return returnData; -} -/// -///登录 -/// -public async Task LoginAsync(System.String account,System.String password,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{account,password}; -return (System.Boolean) await Client.InvokeAsync(typeof(System.Boolean),"Login",invokeOption, parameters); -} + /// + ///性能测试 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + System.Int32 Performance(System.Int32 a, IInvokeOption invokeOption = default); -/// -///注册 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public System.Boolean Register(RegisterModel register,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{register}; -System.Boolean returnData=(System.Boolean)Client.Invoke(typeof(System.Boolean),"Register",invokeOption, parameters); -return returnData; -} -/// -///注册 -/// -public async Task RegisterAsync(RegisterModel register,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{register}; -return (System.Boolean) await Client.InvokeAsync(typeof(System.Boolean),"Register",invokeOption, parameters); -} + /// + ///性能测试 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task PerformanceAsync(System.Int32 a, IInvokeOption invokeOption = default); -/// -///性能测试 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public System.Int32 Performance(System.Int32 a,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{a}; -System.Int32 returnData=(System.Int32)Client.Invoke(typeof(System.Int32),"Performance",invokeOption, parameters); -return returnData; -} -/// -///性能测试 -/// -public async Task PerformanceAsync(System.Int32 a,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{a}; -return (System.Int32) await Client.InvokeAsync(typeof(System.Int32),"Performance",invokeOption, parameters); -} + /// + ///测试out + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + System.Boolean OutBytes(out System.Byte[] bytes, IInvokeOption invokeOption = default); -/// -///测试out -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public System.Boolean OutBytes(out System.Byte[] bytes,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{default(System.Byte[])}; -Type[] types = new Type[]{typeof(System.Byte[])}; -System.Boolean returnData=(System.Boolean)Client.Invoke(typeof(System.Boolean),"OutBytes",invokeOption,ref parameters,types); -if(parameters!=null) -{ -bytes=(System.Byte[])parameters[0]; -} -else -{ -bytes=default(System.Byte[]); -} -return returnData; -} -/// -///测试out -/// -public Task OutBytesAsync(out System.Byte[] bytes,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{default(System.Byte[])}; -Type[] types = new Type[]{typeof(System.Byte[])}; -System.Boolean returnData=(System.Boolean)Client.Invoke(typeof(System.Boolean),"OutBytes",invokeOption,ref parameters,types); -if(parameters!=null) -{ -bytes=(System.Byte[])parameters[0]; -} -else -{ -bytes=default(System.Byte[]); -} -return Task.FromResult(returnData); -} + /// + ///测试out + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task OutBytesAsync(out System.Byte[] bytes, IInvokeOption invokeOption = default); + } -} -public static class MyRpcServerExtensions -{ -/// -///登录 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static System.Boolean Login(this TClient client,System.String account,System.String password,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -object[] parameters = new object[]{account,password}; -System.Boolean returnData=(System.Boolean)client.Invoke(typeof(System.Boolean),"Login",invokeOption, parameters); -return returnData; -} -/// -///登录 -/// -public static async Task LoginAsync(this TClient client,System.String account,System.String password,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -object[] parameters = new object[]{account,password}; -return (System.Boolean) await client.InvokeAsync(typeof(System.Boolean),"Login",invokeOption, parameters); -} + public class MyRpcServer : IMyRpcServer + { + public MyRpcServer(IRpcClient client) + { + this.Client = client; + } -/// -///注册 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static System.Boolean Register(this TClient client,RegisterModel register,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -object[] parameters = new object[]{register}; -System.Boolean returnData=(System.Boolean)client.Invoke(typeof(System.Boolean),"Register",invokeOption, parameters); -return returnData; -} -/// -///注册 -/// -public static async Task RegisterAsync(this TClient client,RegisterModel register,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -object[] parameters = new object[]{register}; -return (System.Boolean) await client.InvokeAsync(typeof(System.Boolean),"Register",invokeOption, parameters); -} + public IRpcClient Client { get; private set; } -/// -///性能测试 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static System.Int32 Performance(this TClient client,System.Int32 a,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -object[] parameters = new object[]{a}; -System.Int32 returnData=(System.Int32)client.Invoke(typeof(System.Int32),"Performance",invokeOption, parameters); -return returnData; -} -/// -///性能测试 -/// -public static async Task PerformanceAsync(this TClient client,System.Int32 a,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -object[] parameters = new object[]{a}; -return (System.Int32) await client.InvokeAsync(typeof(System.Int32),"Performance",invokeOption, parameters); -} + /// + ///登录 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public System.Boolean Login(System.String account, System.String password, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { account, password }; + System.Boolean returnData = (System.Boolean)Client.Invoke(typeof(System.Boolean), "Login", invokeOption, parameters); + return returnData; + } -/// -///测试out -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static System.Boolean OutBytes(this TClient client,out System.Byte[] bytes,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -object[] parameters = new object[]{default(System.Byte[])}; -Type[] types = new Type[]{typeof(System.Byte[])}; -System.Boolean returnData=(System.Boolean)client.Invoke(typeof(System.Boolean),"OutBytes",invokeOption,ref parameters,types); -if(parameters!=null) -{ -bytes=(System.Byte[])parameters[0]; -} -else -{ -bytes=default(System.Byte[]); -} -return returnData; -} -/// -///测试out -/// -public static Task OutBytesAsync(this TClient client,out System.Byte[] bytes,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -object[] parameters = new object[]{default(System.Byte[])}; -Type[] types = new Type[]{typeof(System.Byte[])}; -System.Boolean returnData=(System.Boolean)client.Invoke(typeof(System.Boolean),"OutBytes",invokeOption,ref parameters,types); -if(parameters!=null) -{ -bytes=(System.Byte[])parameters[0]; -} -else -{ -bytes=default(System.Byte[]); -} -return Task.FromResult(returnData); -} + /// + ///登录 + /// + public async Task LoginAsync(System.String account, System.String password, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { account, password }; + return (System.Boolean)await Client.InvokeAsync(typeof(System.Boolean), "Login", invokeOption, parameters); + } -} + /// + ///注册 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public System.Boolean Register(RegisterModel register, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { register }; + System.Boolean returnData = (System.Boolean)Client.Invoke(typeof(System.Boolean), "Register", invokeOption, parameters); + return returnData; + } -public class RegisterModel -{ -public System.String Account{get;set;} -public System.String Password{get;set;} -public System.Int32 Id{get;set;} -} + /// + ///注册 + /// + public async Task RegisterAsync(RegisterModel register, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { register }; + return (System.Boolean)await Client.InvokeAsync(typeof(System.Boolean), "Register", invokeOption, parameters); + } -} + /// + ///性能测试 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public System.Int32 Performance(System.Int32 a, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { a }; + System.Int32 returnData = (System.Int32)Client.Invoke(typeof(System.Int32), "Performance", invokeOption, parameters); + return returnData; + } + + /// + ///性能测试 + /// + public async Task PerformanceAsync(System.Int32 a, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { a }; + return (System.Int32)await Client.InvokeAsync(typeof(System.Int32), "Performance", invokeOption, parameters); + } + + /// + ///测试out + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public System.Boolean OutBytes(out System.Byte[] bytes, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { default(System.Byte[]) }; + Type[] types = new Type[] { typeof(System.Byte[]) }; + System.Boolean returnData = (System.Boolean)Client.Invoke(typeof(System.Boolean), "OutBytes", invokeOption, ref parameters, types); + if (parameters != null) + { + bytes = (System.Byte[])parameters[0]; + } + else + { + bytes = default(System.Byte[]); + } + return returnData; + } + + /// + ///测试out + /// + public Task OutBytesAsync(out System.Byte[] bytes, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { default(System.Byte[]) }; + Type[] types = new Type[] { typeof(System.Byte[]) }; + System.Boolean returnData = (System.Boolean)Client.Invoke(typeof(System.Boolean), "OutBytes", invokeOption, ref parameters, types); + if (parameters != null) + { + bytes = (System.Byte[])parameters[0]; + } + else + { + bytes = default(System.Byte[]); + } + return Task.FromResult(returnData); + } + } + + public static class MyRpcServerExtensions + { + /// + ///登录 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static System.Boolean Login(this TClient client, System.String account, System.String password, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + object[] parameters = new object[] { account, password }; + System.Boolean returnData = (System.Boolean)client.Invoke(typeof(System.Boolean), "Login", invokeOption, parameters); + return returnData; + } + + /// + ///登录 + /// + public static async Task LoginAsync(this TClient client, System.String account, System.String password, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + object[] parameters = new object[] { account, password }; + return (System.Boolean)await client.InvokeAsync(typeof(System.Boolean), "Login", invokeOption, parameters); + } + + /// + ///注册 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static System.Boolean Register(this TClient client, RegisterModel register, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + object[] parameters = new object[] { register }; + System.Boolean returnData = (System.Boolean)client.Invoke(typeof(System.Boolean), "Register", invokeOption, parameters); + return returnData; + } + + /// + ///注册 + /// + public static async Task RegisterAsync(this TClient client, RegisterModel register, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + object[] parameters = new object[] { register }; + return (System.Boolean)await client.InvokeAsync(typeof(System.Boolean), "Register", invokeOption, parameters); + } + + /// + ///性能测试 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static System.Int32 Performance(this TClient client, System.Int32 a, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + object[] parameters = new object[] { a }; + System.Int32 returnData = (System.Int32)client.Invoke(typeof(System.Int32), "Performance", invokeOption, parameters); + return returnData; + } + + /// + ///性能测试 + /// + public static async Task PerformanceAsync(this TClient client, System.Int32 a, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + object[] parameters = new object[] { a }; + return (System.Int32)await client.InvokeAsync(typeof(System.Int32), "Performance", invokeOption, parameters); + } + + /// + ///测试out + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static System.Boolean OutBytes(this TClient client, out System.Byte[] bytes, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + object[] parameters = new object[] { default(System.Byte[]) }; + Type[] types = new Type[] { typeof(System.Byte[]) }; + System.Boolean returnData = (System.Boolean)client.Invoke(typeof(System.Boolean), "OutBytes", invokeOption, ref parameters, types); + if (parameters != null) + { + bytes = (System.Byte[])parameters[0]; + } + else + { + bytes = default(System.Byte[]); + } + return returnData; + } + + /// + ///测试out + /// + public static Task OutBytesAsync(this TClient client, out System.Byte[] bytes, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + object[] parameters = new object[] { default(System.Byte[]) }; + Type[] types = new Type[] { typeof(System.Byte[]) }; + System.Boolean returnData = (System.Boolean)client.Invoke(typeof(System.Boolean), "OutBytes", invokeOption, ref parameters, types); + if (parameters != null) + { + bytes = (System.Byte[])parameters[0]; + } + else + { + bytes = default(System.Byte[]); + } + return Task.FromResult(returnData); + } + } + + public class RegisterModel + { + public System.String Account { get; set; } + public System.String Password { get; set; } + public System.Int32 Id { get; set; } + } +} \ No newline at end of file diff --git a/examples/Dmtp/DmtpRpcClientConsoleApp/Program.cs b/examples/Dmtp/DmtpRpcClientConsoleApp/Program.cs index 911c934d0..b2b9520a7 100644 --- a/examples/Dmtp/DmtpRpcClientConsoleApp/Program.cs +++ b/examples/Dmtp/DmtpRpcClientConsoleApp/Program.cs @@ -10,7 +10,7 @@ namespace ClientConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var consoleAction = new ConsoleAction(); consoleAction.OnException += ConsoleAction_OnException; @@ -32,13 +32,12 @@ namespace ClientConsoleApp } } - private static void ConsoleAction_OnException(Exception obj) { ConsoleLogger.Default.Exception(obj); } - static void RunInvokeCancellationToken() + private static void RunInvokeCancellationToken() { var client = GetTcpDmtpClient(); @@ -70,7 +69,7 @@ namespace ClientConsoleApp /// /// 客户端互相调用Rpc /// - static void RunInvokeT_2C() + private static void RunInvokeT_2C() { var client1 = GetTcpDmtpClient(); var client2 = GetTcpDmtpClient(); @@ -85,7 +84,7 @@ namespace ClientConsoleApp /// /// 直接调用Rpc /// - static void RunInvokeT() + private static void RunInvokeT() { var client = GetTcpDmtpClient(); @@ -103,7 +102,7 @@ namespace ClientConsoleApp client.Logger.Info($"调用Add方法成功,结果:{sum}"); } - static async void RunRpcPullChannel() + private static async void RunRpcPullChannel() { using var client = GetTcpDmtpClient(); var status = ChannelStatus.Default; @@ -148,8 +147,7 @@ namespace ClientConsoleApp Console.WriteLine($"状态:{status},result={result}"); } - - static TcpDmtpClient GetTcpDmtpClient() + private static TcpDmtpClient GetTcpDmtpClient() { var client = new TcpDmtpClient(); client.Setup(new TouchSocketConfig() @@ -165,7 +163,7 @@ namespace ClientConsoleApp { a.UseDmtpRpc() //.SetSerializationSelector(new MySerializationSelector())//自定义序列化器 - .SetCreateDmtpRpcActor((actor, serverprovider,resolver) => new MyDmtpRpcActor(actor, serverprovider, resolver)); + .SetCreateDmtpRpcActor((actor, serverprovider, resolver) => new MyDmtpRpcActor(actor, serverprovider, resolver)); a.UseDmtpHeartbeat() .SetTick(TimeSpan.FromSeconds(3)) @@ -178,34 +176,30 @@ namespace ClientConsoleApp })); client.Connect(); - IRpcClient1 rpcClient1 = client.GetDmtpRpcActor(); - IRpcClient2 rpcClient2 = client.GetDmtpRpcActor(); + var rpcClient1 = client.GetDmtpRpcActor(); + var rpcClient2 = client.GetDmtpRpcActor(); client.Logger.Info($"连接成功,Id={client.Id}"); return client; } - - } - interface IRpcClient1 : IDmtpRpcActor + internal interface IRpcClient1 : IDmtpRpcActor { - } - interface IRpcClient2 : IDmtpRpcActor + internal interface IRpcClient2 : IDmtpRpcActor { - } - class MyDmtpRpcActor : DmtpRpcActor, IRpcClient1, IRpcClient2 + internal class MyDmtpRpcActor : DmtpRpcActor, IRpcClient1, IRpcClient2 { public MyDmtpRpcActor(IDmtpActor smtpActor, IRpcServerProvider rpcServerProvider, IResolver resolver) : base(smtpActor, rpcServerProvider, resolver) { } } - partial class MyClientRpcServer : RpcServer + internal partial class MyClientRpcServer : RpcServer { private readonly ILog m_logger; diff --git a/examples/Dmtp/DmtpRpcServerConsoleApp/Program.cs b/examples/Dmtp/DmtpRpcServerConsoleApp/Program.cs index 8a162dad2..14ad41c9b 100644 --- a/examples/Dmtp/DmtpRpcServerConsoleApp/Program.cs +++ b/examples/Dmtp/DmtpRpcServerConsoleApp/Program.cs @@ -5,13 +5,13 @@ using TouchSocket.Dmtp.Rpc; using TouchSocket.Rpc; using TouchSocket.Sockets; -[assembly:GeneratorRpcServerRegister]//生成注册 +[assembly: GeneratorRpcServerRegister]//生成注册 namespace ConsoleApp2 { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var service = new TcpDmtpService(); var config = new TouchSocketConfig()//配置 @@ -23,8 +23,6 @@ namespace ConsoleApp2 a.AddRpcStore(store => { - - store.RegisterServer(); #if DEBUG File.WriteAllText("../../../RpcProxy.cs", store.GetProxyCodes("RpcProxy", new Type[] { typeof(DmtpRpcAttribute) })); @@ -46,7 +44,6 @@ namespace ConsoleApp2 service.Setup(config); service.Start(); - service.Logger.Info($"{service.GetType().Name}已启动"); service.Logger.Info($"输入客户端Id,空格输入消息,将通知客户端方法"); @@ -60,7 +57,6 @@ namespace ConsoleApp2 service.Logger.Info($"调用结果{result}"); } } - } } diff --git a/examples/Dmtp/DmtpRpcServerConsoleApp/RpcProxy.cs b/examples/Dmtp/DmtpRpcServerConsoleApp/RpcProxy.cs index fb9c91165..70335e5dc 100644 --- a/examples/Dmtp/DmtpRpcServerConsoleApp/RpcProxy.cs +++ b/examples/Dmtp/DmtpRpcServerConsoleApp/RpcProxy.cs @@ -2,284 +2,307 @@ 此代码由Rpc工具直接生成,非必要请不要修改此处代码 */ #pragma warning disable + using System; -using TouchSocket.Core; -using TouchSocket.Sockets; -using TouchSocket.Rpc; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading.Tasks; +using TouchSocket.Core; +using TouchSocket.Rpc; +using TouchSocket.Sockets; + namespace RpcProxy { -public interface IMyRpcServer:TouchSocket.Rpc.IRemoteServer -{ -/// -///将两个数相加 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -System.Int32 Add(System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default); -/// -///将两个数相加 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task AddAsync(System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default); + public interface IMyRpcServer : TouchSocket.Rpc.IRemoteServer + { + /// + ///将两个数相加 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + System.Int32 Add(System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default); -/// -///测试客户端请求,服务器响应大量流数据 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -System.Int32 RpcPullChannel(System.Int32 channelID,IInvokeOption invokeOption = default); -/// -///测试客户端请求,服务器响应大量流数据 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task RpcPullChannelAsync(System.Int32 channelID,IInvokeOption invokeOption = default); + /// + ///将两个数相加 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task AddAsync(System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default); -/// -///测试客户端推送流数据 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -System.Int32 RpcPushChannel(System.Int32 channelID,IInvokeOption invokeOption = default); -/// -///测试客户端推送流数据 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task RpcPushChannelAsync(System.Int32 channelID,IInvokeOption invokeOption = default); + /// + ///测试客户端请求,服务器响应大量流数据 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + System.Int32 RpcPullChannel(System.Int32 channelID, IInvokeOption invokeOption = default); -/// -///测试取消调用 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Int32 TestCancellationToken(IInvokeOption invokeOption = default); -/// -///测试取消调用 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task TestCancellationTokenAsync(IInvokeOption invokeOption = default); + /// + ///测试客户端请求,服务器响应大量流数据 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task RpcPullChannelAsync(System.Int32 channelID, IInvokeOption invokeOption = default); -} -public class MyRpcServer :IMyRpcServer -{ -public MyRpcServer(IRpcClient client) -{ -this.Client=client; -} -public IRpcClient Client{get;private set; } -/// -///将两个数相加 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public System.Int32 Add(System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{a,b}; -System.Int32 returnData=(System.Int32)Client.Invoke(typeof(System.Int32),"Add",invokeOption, parameters); -return returnData; -} -/// -///将两个数相加 -/// -public async Task AddAsync(System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{a,b}; -return (System.Int32) await Client.InvokeAsync(typeof(System.Int32),"Add",invokeOption, parameters); -} + /// + ///测试客户端推送流数据 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + System.Int32 RpcPushChannel(System.Int32 channelID, IInvokeOption invokeOption = default); -/// -///测试客户端请求,服务器响应大量流数据 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public System.Int32 RpcPullChannel(System.Int32 channelID,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{channelID}; -System.Int32 returnData=(System.Int32)Client.Invoke(typeof(System.Int32),"consoleapp2.myrpcserver.rpcpullchannel",invokeOption, parameters); -return returnData; -} -/// -///测试客户端请求,服务器响应大量流数据 -/// -public async Task RpcPullChannelAsync(System.Int32 channelID,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{channelID}; -return (System.Int32) await Client.InvokeAsync(typeof(System.Int32),"consoleapp2.myrpcserver.rpcpullchannel",invokeOption, parameters); -} + /// + ///测试客户端推送流数据 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task RpcPushChannelAsync(System.Int32 channelID, IInvokeOption invokeOption = default); -/// -///测试客户端推送流数据 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public System.Int32 RpcPushChannel(System.Int32 channelID,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{channelID}; -System.Int32 returnData=(System.Int32)Client.Invoke(typeof(System.Int32),"consoleapp2.myrpcserver.rpcpushchannel",invokeOption, parameters); -return returnData; -} -/// -///测试客户端推送流数据 -/// -public async Task RpcPushChannelAsync(System.Int32 channelID,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{channelID}; -return (System.Int32) await Client.InvokeAsync(typeof(System.Int32),"consoleapp2.myrpcserver.rpcpushchannel",invokeOption, parameters); -} + /// + ///测试取消调用 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Int32 TestCancellationToken(IInvokeOption invokeOption = default); -/// -///测试取消调用 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public Int32 TestCancellationToken(IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -Int32 returnData=(Int32)Client.Invoke(typeof(Int32),"consoleapp2.myrpcserver.testcancellationtoken",invokeOption, null); -return returnData; -} -/// -///测试取消调用 -/// -public async Task TestCancellationTokenAsync(IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -return (Int32) await Client.InvokeAsync(typeof(Int32),"consoleapp2.myrpcserver.testcancellationtoken",invokeOption, null); -} + /// + ///测试取消调用 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task TestCancellationTokenAsync(IInvokeOption invokeOption = default); + } -} -public static class MyRpcServerExtensions -{ -/// -///将两个数相加 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static System.Int32 Add(this TClient client,System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -object[] parameters = new object[]{a,b}; -System.Int32 returnData=(System.Int32)client.Invoke(typeof(System.Int32),"Add",invokeOption, parameters); -return returnData; -} -/// -///将两个数相加 -/// -public static async Task AddAsync(this TClient client,System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -object[] parameters = new object[]{a,b}; -return (System.Int32) await client.InvokeAsync(typeof(System.Int32),"Add",invokeOption, parameters); -} + public class MyRpcServer : IMyRpcServer + { + public MyRpcServer(IRpcClient client) + { + this.Client = client; + } -/// -///测试客户端请求,服务器响应大量流数据 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static System.Int32 RpcPullChannel(this TClient client,System.Int32 channelID,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -object[] parameters = new object[]{channelID}; -System.Int32 returnData=(System.Int32)client.Invoke(typeof(System.Int32),"consoleapp2.myrpcserver.rpcpullchannel",invokeOption, parameters); -return returnData; -} -/// -///测试客户端请求,服务器响应大量流数据 -/// -public static async Task RpcPullChannelAsync(this TClient client,System.Int32 channelID,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -object[] parameters = new object[]{channelID}; -return (System.Int32) await client.InvokeAsync(typeof(System.Int32),"consoleapp2.myrpcserver.rpcpullchannel",invokeOption, parameters); -} + public IRpcClient Client { get; private set; } -/// -///测试客户端推送流数据 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static System.Int32 RpcPushChannel(this TClient client,System.Int32 channelID,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -object[] parameters = new object[]{channelID}; -System.Int32 returnData=(System.Int32)client.Invoke(typeof(System.Int32),"consoleapp2.myrpcserver.rpcpushchannel",invokeOption, parameters); -return returnData; -} -/// -///测试客户端推送流数据 -/// -public static async Task RpcPushChannelAsync(this TClient client,System.Int32 channelID,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -object[] parameters = new object[]{channelID}; -return (System.Int32) await client.InvokeAsync(typeof(System.Int32),"consoleapp2.myrpcserver.rpcpushchannel",invokeOption, parameters); -} + /// + ///将两个数相加 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public System.Int32 Add(System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { a, b }; + System.Int32 returnData = (System.Int32)Client.Invoke(typeof(System.Int32), "Add", invokeOption, parameters); + return returnData; + } -/// -///测试取消调用 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static Int32 TestCancellationToken(this TClient client,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -Int32 returnData=(Int32)client.Invoke(typeof(Int32),"consoleapp2.myrpcserver.testcancellationtoken",invokeOption, null); -return returnData; -} -/// -///测试取消调用 -/// -public static async Task TestCancellationTokenAsync(this TClient client,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -return (Int32) await client.InvokeAsync(typeof(Int32),"consoleapp2.myrpcserver.testcancellationtoken",invokeOption, null); -} + /// + ///将两个数相加 + /// + public async Task AddAsync(System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { a, b }; + return (System.Int32)await Client.InvokeAsync(typeof(System.Int32), "Add", invokeOption, parameters); + } -} -} + /// + ///测试客户端请求,服务器响应大量流数据 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public System.Int32 RpcPullChannel(System.Int32 channelID, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { channelID }; + System.Int32 returnData = (System.Int32)Client.Invoke(typeof(System.Int32), "consoleapp2.myrpcserver.rpcpullchannel", invokeOption, parameters); + return returnData; + } + + /// + ///测试客户端请求,服务器响应大量流数据 + /// + public async Task RpcPullChannelAsync(System.Int32 channelID, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { channelID }; + return (System.Int32)await Client.InvokeAsync(typeof(System.Int32), "consoleapp2.myrpcserver.rpcpullchannel", invokeOption, parameters); + } + + /// + ///测试客户端推送流数据 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public System.Int32 RpcPushChannel(System.Int32 channelID, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { channelID }; + System.Int32 returnData = (System.Int32)Client.Invoke(typeof(System.Int32), "consoleapp2.myrpcserver.rpcpushchannel", invokeOption, parameters); + return returnData; + } + + /// + ///测试客户端推送流数据 + /// + public async Task RpcPushChannelAsync(System.Int32 channelID, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { channelID }; + return (System.Int32)await Client.InvokeAsync(typeof(System.Int32), "consoleapp2.myrpcserver.rpcpushchannel", invokeOption, parameters); + } + + /// + ///测试取消调用 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public Int32 TestCancellationToken(IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + Int32 returnData = (Int32)Client.Invoke(typeof(Int32), "consoleapp2.myrpcserver.testcancellationtoken", invokeOption, null); + return returnData; + } + + /// + ///测试取消调用 + /// + public async Task TestCancellationTokenAsync(IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + return (Int32)await Client.InvokeAsync(typeof(Int32), "consoleapp2.myrpcserver.testcancellationtoken", invokeOption, null); + } + } + + public static class MyRpcServerExtensions + { + /// + ///将两个数相加 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static System.Int32 Add(this TClient client, System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + object[] parameters = new object[] { a, b }; + System.Int32 returnData = (System.Int32)client.Invoke(typeof(System.Int32), "Add", invokeOption, parameters); + return returnData; + } + + /// + ///将两个数相加 + /// + public static async Task AddAsync(this TClient client, System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + object[] parameters = new object[] { a, b }; + return (System.Int32)await client.InvokeAsync(typeof(System.Int32), "Add", invokeOption, parameters); + } + + /// + ///测试客户端请求,服务器响应大量流数据 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static System.Int32 RpcPullChannel(this TClient client, System.Int32 channelID, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + object[] parameters = new object[] { channelID }; + System.Int32 returnData = (System.Int32)client.Invoke(typeof(System.Int32), "consoleapp2.myrpcserver.rpcpullchannel", invokeOption, parameters); + return returnData; + } + + /// + ///测试客户端请求,服务器响应大量流数据 + /// + public static async Task RpcPullChannelAsync(this TClient client, System.Int32 channelID, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + object[] parameters = new object[] { channelID }; + return (System.Int32)await client.InvokeAsync(typeof(System.Int32), "consoleapp2.myrpcserver.rpcpullchannel", invokeOption, parameters); + } + + /// + ///测试客户端推送流数据 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static System.Int32 RpcPushChannel(this TClient client, System.Int32 channelID, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + object[] parameters = new object[] { channelID }; + System.Int32 returnData = (System.Int32)client.Invoke(typeof(System.Int32), "consoleapp2.myrpcserver.rpcpushchannel", invokeOption, parameters); + return returnData; + } + + /// + ///测试客户端推送流数据 + /// + public static async Task RpcPushChannelAsync(this TClient client, System.Int32 channelID, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + object[] parameters = new object[] { channelID }; + return (System.Int32)await client.InvokeAsync(typeof(System.Int32), "consoleapp2.myrpcserver.rpcpushchannel", invokeOption, parameters); + } + + /// + ///测试取消调用 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static Int32 TestCancellationToken(this TClient client, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + Int32 returnData = (Int32)client.Invoke(typeof(Int32), "consoleapp2.myrpcserver.testcancellationtoken", invokeOption, null); + return returnData; + } + + /// + ///测试取消调用 + /// + public static async Task TestCancellationTokenAsync(this TClient client, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + return (Int32)await client.InvokeAsync(typeof(Int32), "consoleapp2.myrpcserver.testcancellationtoken", invokeOption, null); + } + } +} \ No newline at end of file diff --git a/examples/Dmtp/DmtpWebApplication/Program.cs b/examples/Dmtp/DmtpWebApplication/Program.cs index 25553bb39..c8a032197 100644 --- a/examples/Dmtp/DmtpWebApplication/Program.cs +++ b/examples/Dmtp/DmtpWebApplication/Program.cs @@ -1,6 +1,5 @@ using TouchSocket.Core; using TouchSocket.Dmtp; -using TouchSocket.Sockets; namespace DmtpWebApplication { @@ -72,7 +71,7 @@ namespace DmtpWebApplication } } - class MyClassPlugin : PluginBase, IDmtpHandshakedPlugin + internal class MyClassPlugin : PluginBase, IDmtpHandshakedPlugin { private readonly ILogger m_logger; @@ -80,9 +79,10 @@ namespace DmtpWebApplication { this.m_logger = logger; } + public async Task OnDmtpHandshaked(IDmtpActorObject client, DmtpVerifyEventArgs e) { - m_logger.LogInformation("DmtpHandshaked"); + this.m_logger.LogInformation("DmtpHandshaked"); await e.InvokeNext(); } } diff --git a/examples/Dmtp/FileTransferConsoleApp/Program.cs b/examples/Dmtp/FileTransferConsoleApp/Program.cs index 98a732d34..0e8258fa8 100644 --- a/examples/Dmtp/FileTransferConsoleApp/Program.cs +++ b/examples/Dmtp/FileTransferConsoleApp/Program.cs @@ -1,13 +1,10 @@ -using System.Net.Http.Headers; -using TouchSocket.Core; +using TouchSocket.Core; using TouchSocket.Dmtp; using TouchSocket.Dmtp.FileTransfer; -using TouchSocket.Dmtp.Rpc; using TouchSocket.Sockets; namespace FileTransferConsoleApp { - internal class Program { /// @@ -59,7 +56,7 @@ namespace FileTransferConsoleApp /// /// 多线程推送文件 /// - static void MultithreadingClientPushFileFromService() + private static void MultithreadingClientPushFileFromService() { using var clientFactory = CreateClientFactory(); var resultCon = clientFactory.CheckStatus();//检验连接状态,一般当主通行器连接时,即认为在连接状态。 @@ -126,7 +123,7 @@ namespace FileTransferConsoleApp /// /// 多线程请求文件 /// - static void MultithreadingClientPullFileFromService() + private static void MultithreadingClientPullFileFromService() { using var clientFactory = CreateClientFactory(); var resultCon = clientFactory.CheckStatus();//检验连接状态,一般当主通行器连接时,即认为在连接状态。 @@ -192,7 +189,7 @@ namespace FileTransferConsoleApp /// 推送小文件 /// /// - static void PushSmallFileFromService(TcpDmtpClient client) + private static void PushSmallFileFromService(TcpDmtpClient client) { ConsoleLogger.Default.Info("开始从服务器下载小文件"); var filePath = "PushSmallFileFromService.Test"; @@ -228,7 +225,7 @@ namespace FileTransferConsoleApp /// 请求小文件 /// /// - static void PullSmallFileFromService(TcpDmtpClient client) + private static void PullSmallFileFromService(TcpDmtpClient client) { ConsoleLogger.Default.Info("开始从服务器下载小文件"); @@ -269,7 +266,7 @@ namespace FileTransferConsoleApp /// /// 客户端向其他客户端推送文件。 /// - static void ClientPushFileFromClient() + private static void ClientPushFileFromClient() { using var client1 = GetTcpDmtpClient(); using var client2 = GetTcpDmtpClient(); @@ -330,7 +327,7 @@ namespace FileTransferConsoleApp /// /// 客户端从其他客户端下载文件。 /// - static void ClientPullFileFromClient() + private static void ClientPullFileFromClient() { using var client1 = GetTcpDmtpClient(); using var client2 = GetTcpDmtpClient(); @@ -393,7 +390,7 @@ namespace FileTransferConsoleApp /// /// 服务器 /// 服务器要请求的客户端Id - static void ServicePushFileFromClient(TcpDmtpService service, string targetId) + private static void ServicePushFileFromClient(TcpDmtpService service, string targetId) { if (!service.TryGetSocketClient(targetId, out var socketClient)) { @@ -458,7 +455,7 @@ namespace FileTransferConsoleApp /// /// 服务器 /// 服务器要请求的客户端Id - static void ServicePullFileFromClient(TcpDmtpService service, string targetId) + private static void ServicePullFileFromClient(TcpDmtpService service, string targetId) { if (!service.TryGetSocketClient(targetId, out var socketClient)) { @@ -522,7 +519,7 @@ namespace FileTransferConsoleApp /// 客户端从服务器下载文件。 /// /// - static void ClientPullFileFromService(TcpDmtpClient client) + private static void ClientPullFileFromService(TcpDmtpClient client) { ConsoleLogger.Default.Info("开始从服务器下载文件"); @@ -605,7 +602,7 @@ namespace FileTransferConsoleApp /// 客户端上传文件到服务器。 /// /// - static void ClientPushFileFromService(TcpDmtpClient client) + private static void ClientPushFileFromService(TcpDmtpClient client) { ConsoleLogger.Default.Info("上传文件到服务器"); @@ -769,8 +766,6 @@ namespace FileTransferConsoleApp } } - - internal class MyPlugin : PluginBase, IDmtpFileTransferingPlugin, IDmtpFileTransferedPlugin, IDmtpRoutingPlugin { private readonly ILog m_logger; @@ -805,7 +800,7 @@ namespace FileTransferConsoleApp /// 该方法,会在每个文件被请求(推送)时第一时间触发。 /// 当请求文件时,可以重新指定请求的文件路径,即对e.ResourcePath直接赋值。 /// 当推送文件时,可以重新指定保存文件路径,即对e.SavePath直接赋值。 - /// + /// /// 注意:当文件夹不存在时,需要手动创建。 /// /// @@ -839,5 +834,4 @@ namespace FileTransferConsoleApp await e.InvokeNext(); } } - } \ No newline at end of file diff --git a/examples/Dmtp/NamedPipeDmtpConsoleApp/Program.cs b/examples/Dmtp/NamedPipeDmtpConsoleApp/Program.cs index f1fd85e6a..3e8b63519 100644 --- a/examples/Dmtp/NamedPipeDmtpConsoleApp/Program.cs +++ b/examples/Dmtp/NamedPipeDmtpConsoleApp/Program.cs @@ -7,7 +7,7 @@ namespace NamedPipeDmtpConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { try { @@ -23,7 +23,7 @@ namespace NamedPipeDmtpConsoleApp Console.ReadKey(); } - static NamedPipeDmtpClient GetClient() + private static NamedPipeDmtpClient GetClient() { var client = new NamedPipeDmtpClient(); client.Setup(new TouchSocketConfig() @@ -42,7 +42,7 @@ namespace NamedPipeDmtpConsoleApp return client; } - static NamedPipeDmtpService GetService() + private static NamedPipeDmtpService GetService() { var service = new NamedPipeDmtpService(); var config = new TouchSocketConfig()//配置 @@ -65,4 +65,4 @@ namespace NamedPipeDmtpConsoleApp return service; } } -} +} \ No newline at end of file diff --git a/examples/Dmtp/RealityProxyDmtpRpcConsoleApp/Program.cs b/examples/Dmtp/RealityProxyDmtpRpcConsoleApp/Program.cs index a84d8ecdf..1b9f83725 100644 --- a/examples/Dmtp/RealityProxyDmtpRpcConsoleApp/Program.cs +++ b/examples/Dmtp/RealityProxyDmtpRpcConsoleApp/Program.cs @@ -1,7 +1,7 @@ using System; using TouchSocket.Core; -using TouchSocket.Dmtp.Rpc; using TouchSocket.Dmtp; +using TouchSocket.Dmtp.Rpc; using TouchSocket.Sockets; namespace RealityProxyDmtpRpcConsoleApp @@ -11,10 +11,10 @@ namespace RealityProxyDmtpRpcConsoleApp /// internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var myDmtpRpcRealityProxy = new MyDmtpRpcRealityProxy(); - + var myRpcServer = myDmtpRpcRealityProxy.GetTransparentProxy(); var result = myRpcServer.Add(10, 20); @@ -27,7 +27,7 @@ namespace RealityProxyDmtpRpcConsoleApp /// 新建一个类,按照需要,继承DmtpRpcRealityProxy,亦或者RpcRealityProxy基类。 /// 然后实现抽象方法,主要是能获取到调用的IRpcClient派生接口。 /// - class MyDmtpRpcRealityProxy : DmtpRpcRealityProxy + internal class MyDmtpRpcRealityProxy : DmtpRpcRealityProxy { private readonly TcpDmtpClient m_client; @@ -60,11 +60,11 @@ namespace RealityProxyDmtpRpcConsoleApp public override IDmtpRpcActor GetClient() { - return m_client.GetDmtpRpcActor(); + return this.m_client.GetDmtpRpcActor(); } } - interface IMyRpcServer + internal interface IMyRpcServer { /// /// 将两个数相加 diff --git a/examples/Dmtp/RecommendRpcConsoleApp/Program.cs b/examples/Dmtp/RecommendRpcConsoleApp/Program.cs index 1292c6489..f5ffec614 100644 --- a/examples/Dmtp/RecommendRpcConsoleApp/Program.cs +++ b/examples/Dmtp/RecommendRpcConsoleApp/Program.cs @@ -1,5 +1,4 @@ -using RpcImplementationClassLibrary; -using TouchSocket.Core; +using TouchSocket.Core; using TouchSocket.Dmtp; using TouchSocket.Dmtp.Rpc; using TouchSocket.Rpc; diff --git a/examples/Dmtp/RemoteStreamConsoleApp/Program.cs b/examples/Dmtp/RemoteStreamConsoleApp/Program.cs index 5fe4e401b..786988976 100644 --- a/examples/Dmtp/RemoteStreamConsoleApp/Program.cs +++ b/examples/Dmtp/RemoteStreamConsoleApp/Program.cs @@ -52,7 +52,6 @@ namespace RemoteStreamConsoleApp { Console.ReadKey(); } - } private static TcpDmtpClient GetTcpDmtpClient() diff --git a/examples/Dmtp/RouterPackageConsoleApp/Program.cs b/examples/Dmtp/RouterPackageConsoleApp/Program.cs index 0632d65a5..d00b38f5d 100644 --- a/examples/Dmtp/RouterPackageConsoleApp/Program.cs +++ b/examples/Dmtp/RouterPackageConsoleApp/Program.cs @@ -7,7 +7,7 @@ namespace RouterPackageConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { try { @@ -20,7 +20,6 @@ namespace RouterPackageConsoleApp } var service = GetTcpDmtpService(); - var consoleAction = new ConsoleAction(); consoleAction.OnException += ConsoleAction_OnException; @@ -131,7 +130,7 @@ namespace RouterPackageConsoleApp /// /// 定义请求包 /// - class MyRequestPackage : DmtpRouterPackage + private class MyRequestPackage : DmtpRouterPackage { /// /// 包尺寸大小。此值并非需要精准数值,只需要估计数据即可。其作用为申请内存池。所以数据应当大小合适。 @@ -159,7 +158,7 @@ namespace RouterPackageConsoleApp /// /// 定义响应包 /// - class MyResponsePackage : DmtpRouterPackage + private class MyResponsePackage : DmtpRouterPackage { /// /// 包尺寸大小。此值并非需要精准数值,只需要估计数据即可。其作用为申请内存池。所以数据应当大小合适。 @@ -167,7 +166,7 @@ namespace RouterPackageConsoleApp public override int PackageSize => 1024; } - class MyPlugin1 : PluginBase, IDmtpRouterPackagePlugin + private class MyPlugin1 : PluginBase, IDmtpRouterPackagePlugin { private readonly ILog m_logger; @@ -175,6 +174,7 @@ namespace RouterPackageConsoleApp { this.m_logger = logger; } + public async Task OnReceivedRouterPackage(IDmtpActorObject client, RouterPackageEventArgs e) { if (e.Metadata?["a"] == "a") @@ -193,13 +193,12 @@ namespace RouterPackageConsoleApp this.m_logger.Info($"已响应包请求"); } - //一般在当前插件无法处理时调用下一插件。 await e.InvokeNext(); } } - class MyPlugin2 : PluginBase, IDmtpRouterPackagePlugin + private class MyPlugin2 : PluginBase, IDmtpRouterPackagePlugin { private readonly ILog m_logger; @@ -207,6 +206,7 @@ namespace RouterPackageConsoleApp { this.m_logger = logger; } + public async Task OnReceivedRouterPackage(IDmtpActorObject client, RouterPackageEventArgs e) { if (e.Metadata?["b"] == "b") @@ -222,7 +222,6 @@ namespace RouterPackageConsoleApp this.m_logger.Info($"已响应包请求"); } - //一般在当前插件无法处理时调用下一插件。 await e.InvokeNext(); } diff --git a/examples/Dmtp/RpcImplementationClassLibrary/AssemblyInfo.cs b/examples/Dmtp/RpcImplementationClassLibrary/AssemblyInfo.cs index 7e7ff7790..400990bad 100644 --- a/examples/Dmtp/RpcImplementationClassLibrary/AssemblyInfo.cs +++ b/examples/Dmtp/RpcImplementationClassLibrary/AssemblyInfo.cs @@ -1,3 +1,3 @@ using TouchSocket.Rpc; -[assembly: GeneratorRpcServerRegister] +[assembly: GeneratorRpcServerRegister] \ No newline at end of file diff --git a/examples/Dmtp/RpcImplementationClassLibrary/UserServer.cs b/examples/Dmtp/RpcImplementationClassLibrary/UserServer.cs index 526fd8127..f301f89ea 100644 --- a/examples/Dmtp/RpcImplementationClassLibrary/UserServer.cs +++ b/examples/Dmtp/RpcImplementationClassLibrary/UserServer.cs @@ -1,6 +1,5 @@ using RpcClassLibrary.Models; using RpcClassLibrary.ServerInterface; -using System; using TouchSocket.Core; using TouchSocket.Rpc; diff --git a/examples/Hosting/HostingWorkerService/Program.cs b/examples/Hosting/HostingWorkerService/Program.cs index ea170fefc..7bf10649f 100644 --- a/examples/Hosting/HostingWorkerService/Program.cs +++ b/examples/Hosting/HostingWorkerService/Program.cs @@ -1,5 +1,3 @@ -using Microsoft.Extensions.DependencyInjection; -using TouchSocket.Core; using TouchSocket.NamedPipe; using TouchSocket.Sockets; @@ -43,13 +41,11 @@ namespace HostingWorkerService } } - class MyTcpService : TcpService, IMyTcpService + internal class MyTcpService : TcpService, IMyTcpService { - } - interface IMyTcpService : ITcpService + internal interface IMyTcpService : ITcpService { - } } \ No newline at end of file diff --git a/examples/Hosting/HostingWorkerService/Properties/launchSettings.json b/examples/Hosting/HostingWorkerService/Properties/launchSettings.json index 86ea331da..b00529b7e 100644 --- a/examples/Hosting/HostingWorkerService/Properties/launchSettings.json +++ b/examples/Hosting/HostingWorkerService/Properties/launchSettings.json @@ -8,4 +8,4 @@ } } } -} +} \ No newline at end of file diff --git a/examples/Hosting/HostingWorkerService/appsettings.Development.json b/examples/Hosting/HostingWorkerService/appsettings.Development.json index b2dcdb674..07c8e4cc6 100644 --- a/examples/Hosting/HostingWorkerService/appsettings.Development.json +++ b/examples/Hosting/HostingWorkerService/appsettings.Development.json @@ -5,4 +5,4 @@ "Microsoft.Hosting.Lifetime": "Information" } } -} +} \ No newline at end of file diff --git a/examples/Hosting/HostingWorkerService/appsettings.json b/examples/Hosting/HostingWorkerService/appsettings.json index b2dcdb674..07c8e4cc6 100644 --- a/examples/Hosting/HostingWorkerService/appsettings.json +++ b/examples/Hosting/HostingWorkerService/appsettings.json @@ -5,4 +5,4 @@ "Microsoft.Hosting.Lifetime": "Information" } } -} +} \ No newline at end of file diff --git a/examples/Http/HttpClientConsoleApp/Program.cs b/examples/Http/HttpClientConsoleApp/Program.cs index 88e1272ac..521253804 100644 --- a/examples/Http/HttpClientConsoleApp/Program.cs +++ b/examples/Http/HttpClientConsoleApp/Program.cs @@ -7,7 +7,7 @@ namespace ClientConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var client = new HttpClient(); client.Setup(new TouchSocketConfig() @@ -22,7 +22,7 @@ namespace ClientConsoleApp .SetHost(client.RemoteIPHost.Host) .AsGet(); - var respose = client.Request(request, false,1000 * 10); + var respose = client.Request(request, false, 1000 * 10); Console.WriteLine(respose.GetBody());//将接收的数据,一次性转为utf8编码的字符串 } @@ -39,7 +39,6 @@ namespace ClientConsoleApp //一次性接收字节 if (respose.TryGetContent(out var content)) { - } //如果数据太大,可以一直read diff --git a/examples/Http/HttpServiceConsoleApp/Program.cs b/examples/Http/HttpServiceConsoleApp/Program.cs index 68eae9b0a..79b1fa868 100644 --- a/examples/Http/HttpServiceConsoleApp/Program.cs +++ b/examples/Http/HttpServiceConsoleApp/Program.cs @@ -178,7 +178,7 @@ namespace ConsoleApp } catch (Exception ex) { - e.Context.Response.SetStatus(403,ex.Message) + e.Context.Response.SetStatus(403, ex.Message) .FromText(ex.Message) .Answer(); } diff --git a/examples/Http/HttpServiceConsoleApp/api/css/index.css b/examples/Http/HttpServiceConsoleApp/api/css/index.css index 8df0b21c3..d3bcfb246 100644 --- a/examples/Http/HttpServiceConsoleApp/api/css/index.css +++ b/examples/Http/HttpServiceConsoleApp/api/css/index.css @@ -31,21 +31,21 @@ header { background-size: 100% 100%; } -header h1 { - font-size: 0.475rem; - color: #fff; - text-align: center; - line-height: 1rem; -} + header h1 { + font-size: 0.475rem; + color: #fff; + text-align: center; + line-height: 1rem; + } -header .showTime { - position: absolute; - top: 0; - right: 0.375rem; - line-height: 0.9375rem; - font-size: 0.25rem; - color: rgba(255, 255, 255, 0.7); -} + header .showTime { + position: absolute; + top: 0; + right: 0.375rem; + line-height: 0.9375rem; + font-size: 0.25rem; + color: rgba(255, 255, 255, 0.7); + } .mainbox { min-width: 1024px; @@ -54,15 +54,15 @@ header .showTime { display: flex; } -.mainbox .column { - flex: 3; -} + .mainbox .column { + flex: 3; + } -.mainbox .column:nth-child(2) { - flex: 5; - margin: 0 0.125rem 0.1875rem; - overflow: hidden; -} + .mainbox .column:nth-child(2) { + flex: 5; + margin: 0 0.125rem 0.1875rem; + overflow: hidden; + } .panel { position: relative; @@ -73,196 +73,196 @@ header .showTime { margin-bottom: 0.1875rem; } -.panel::before { - position: absolute; - top: 0; - left: 0; - content: ""; - width: 10px; - height: 10px; - border-top: 2px solid #02a6b5; - border-left: 2px solid #02a6b5; - border-radius: 20%; -} + .panel::before { + position: absolute; + top: 0; + left: 0; + content: ""; + width: 10px; + height: 10px; + border-top: 2px solid #02a6b5; + border-left: 2px solid #02a6b5; + border-radius: 20%; + } -.panel::after { - position: absolute; - top: 0; - right: 0; - content: ""; - width: 10px; - height: 10px; - border-top: 2px solid #02a6b5; - border-right: 2px solid #02a6b5; - border-radius: 20%; -} + .panel::after { + position: absolute; + top: 0; + right: 0; + content: ""; + width: 10px; + height: 10px; + border-top: 2px solid #02a6b5; + border-right: 2px solid #02a6b5; + border-radius: 20%; + } -.panel .panel-footer { - position: absolute; - left: 0; - bottom: 0; - width: 100%; -} + .panel .panel-footer { + position: absolute; + left: 0; + bottom: 0; + width: 100%; + } -.panel .panel-footer::before { - position: absolute; - bottom: 0; - left: 0; - content: ""; - width: 10px; - height: 10px; - border-bottom: 2px solid #02a6b5; - border-left: 2px solid #02a6b5; - border-radius: 20%; -} + .panel .panel-footer::before { + position: absolute; + bottom: 0; + left: 0; + content: ""; + width: 10px; + height: 10px; + border-bottom: 2px solid #02a6b5; + border-left: 2px solid #02a6b5; + border-radius: 20%; + } -.panel .panel-footer::after { - position: absolute; - bottom: 0; - right: 0; - content: ""; - width: 10px; - height: 10px; - border-bottom: 2px solid #02a6b5; - border-right: 2px solid #02a6b5; - border-radius: 20%; -} + .panel .panel-footer::after { + position: absolute; + bottom: 0; + right: 0; + content: ""; + width: 10px; + height: 10px; + border-bottom: 2px solid #02a6b5; + border-right: 2px solid #02a6b5; + border-radius: 20%; + } -.panel h2 { - height: 0.6rem; - line-height: 0.6rem; - text-align: center; - color: #fff; - font-size: 0.25rem; - font-weight: 400; -} + .panel h2 { + height: 0.6rem; + line-height: 0.6rem; + text-align: center; + color: #fff; + font-size: 0.25rem; + font-weight: 400; + } -.panel h2 a { - margin: 0 0.1875rem; - color: #fff; - text-decoration: underline; -} + .panel h2 a { + margin: 0 0.1875rem; + color: #fff; + text-decoration: underline; + } -.panel .chart { - height: 3rem; -} + .panel .chart { + height: 3rem; + } .no { background: rgba(101, 132, 226, 0.1); padding: 0.1875rem; } -.no .no-hd { - position: relative; - border: 1px solid rgba(25, 186, 139, 0.17); -} + .no .no-hd { + position: relative; + border: 1px solid rgba(25, 186, 139, 0.17); + } -.no .no-hd::before { - content: ""; - position: absolute; - width: 30px; - height: 10px; - border-top: 2px solid #02a6b5; - border-left: 2px solid #02a6b5; - top: 0; - left: 0; -} + .no .no-hd::before { + content: ""; + position: absolute; + width: 30px; + height: 10px; + border-top: 2px solid #02a6b5; + border-left: 2px solid #02a6b5; + top: 0; + left: 0; + } -.no .no-hd::after { - content: ""; - position: absolute; - width: 30px; - height: 10px; - border-bottom: 2px solid #02a6b5; - border-right: 2px solid #02a6b5; - right: 0; - bottom: 0; -} + .no .no-hd::after { + content: ""; + position: absolute; + width: 30px; + height: 10px; + border-bottom: 2px solid #02a6b5; + border-right: 2px solid #02a6b5; + right: 0; + bottom: 0; + } -.no .no-hd ul { - display: flex; -} + .no .no-hd ul { + display: flex; + } -.no .no-hd ul li { - position: relative; - flex: 1; - text-align: center; - height: 1rem; - line-height: 1rem; - font-size: 0.875rem; - color: #ffeb7b; - padding: 0.05rem 0; - font-family: electronicFont; - font-weight: bold; -} + .no .no-hd ul li { + position: relative; + flex: 1; + text-align: center; + height: 1rem; + line-height: 1rem; + font-size: 0.875rem; + color: #ffeb7b; + padding: 0.05rem 0; + font-family: electronicFont; + font-weight: bold; + } -.no .no-hd ul li:first-child::after { - content: ""; - position: absolute; - height: 50%; - width: 1px; - background: rgba(255, 255, 255, 0.2); - right: 0; - top: 25%; -} + .no .no-hd ul li:first-child::after { + content: ""; + position: absolute; + height: 50%; + width: 1px; + background: rgba(255, 255, 255, 0.2); + right: 0; + top: 25%; + } -.no .no-bd ul { - display: flex; -} + .no .no-bd ul { + display: flex; + } -.no .no-bd ul li { - flex: 1; - height: 0.5rem; - line-height: 0.5rem; - text-align: center; - font-size: 0.225rem; - color: rgba(255, 255, 255, 0.7); - padding-top: 0.125rem; -} + .no .no-bd ul li { + flex: 1; + height: 0.5rem; + line-height: 0.5rem; + text-align: center; + font-size: 0.225rem; + color: rgba(255, 255, 255, 0.7); + padding-top: 0.125rem; + } .map { position: relative; height: 10.125rem; } -.map .chart { - position: absolute; - top: 0; - left: 0; - z-index: 5; - height: 10.125rem; - width: 100%; -} + .map .chart { + position: absolute; + top: 0; + left: 0; + z-index: 5; + height: 10.125rem; + width: 100%; + } -.map .map1, -.map .map2, -.map .map3 { - position: absolute; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - width: 6.475rem; - height: 6.475rem; - background: url(../img/map.png) no-repeat; - background-size: 100% 100%; - opacity: 0.3; -} + .map .map1, + .map .map2, + .map .map3 { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + width: 6.475rem; + height: 6.475rem; + background: url(../img/map.png) no-repeat; + background-size: 100% 100%; + opacity: 0.3; + } -.map .map2 { - width: 8.0375rem; - height: 8.0375rem; - background-image: url(../img/lbx.png); - opacity: 0.6; - animation: rotate 15s linear infinite; - z-index: 2; -} + .map .map2 { + width: 8.0375rem; + height: 8.0375rem; + background-image: url(../img/lbx.png); + opacity: 0.6; + animation: rotate 15s linear infinite; + z-index: 2; + } -.map .map3 { - width: 7.075rem; - height: 7.075rem; - background-image: url(../img/jt.png); - animation: rotate1 10s linear infinite; -} + .map .map3 { + width: 7.075rem; + height: 7.075rem; + background-image: url(../img/jt.png); + animation: rotate1 10s linear infinite; + } @keyframes rotate { from { diff --git a/examples/Http/HttpServiceConsoleApp/api/index.html b/examples/Http/HttpServiceConsoleApp/api/index.html index 277e84fb4..52bde1560 100644 --- a/examples/Http/HttpServiceConsoleApp/api/index.html +++ b/examples/Http/HttpServiceConsoleApp/api/index.html @@ -96,8 +96,5 @@ dt.getSeconds() + "秒"; }); - - - \ No newline at end of file diff --git a/examples/Http/HttpServiceForCorsConsoleApp/Program.cs b/examples/Http/HttpServiceForCorsConsoleApp/Program.cs index c65e36df8..dc4ddc94d 100644 --- a/examples/Http/HttpServiceForCorsConsoleApp/Program.cs +++ b/examples/Http/HttpServiceForCorsConsoleApp/Program.cs @@ -6,7 +6,7 @@ namespace HttpServiceForCorsConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var service = new HttpService(); service.Setup(new TouchSocketConfig()//加载配置 @@ -42,4 +42,4 @@ namespace HttpServiceForCorsConsoleApp Console.ReadKey(); } } -} +} \ No newline at end of file diff --git a/examples/JsonRpc/DispatchProxyJsonRpcClientConsoleApp/Program.cs b/examples/JsonRpc/DispatchProxyJsonRpcClientConsoleApp/Program.cs index 176aef036..62ff9f87f 100644 --- a/examples/JsonRpc/DispatchProxyJsonRpcClientConsoleApp/Program.cs +++ b/examples/JsonRpc/DispatchProxyJsonRpcClientConsoleApp/Program.cs @@ -1,14 +1,12 @@ -using Newtonsoft.Json.Linq; -using TouchSocket.Core; +using TouchSocket.Core; using TouchSocket.JsonRpc; using TouchSocket.Sockets; -using TouchSocket.WebApi; namespace DispatchProxyJsonRpcClientConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var rpc = MyJsonRpcDispatchProxy.Create(); @@ -24,7 +22,7 @@ namespace DispatchProxyJsonRpcClientConsoleApp /// 新建一个类,继承JsonRpcDispatchProxy,亦或者RpcDispatchProxy基类。 /// 然后实现抽象方法,主要是能获取到调用的IRpcClient派生接口。 /// - class MyJsonRpcDispatchProxy : JsonRpcDispatchProxy + internal class MyJsonRpcDispatchProxy : JsonRpcDispatchProxy { private readonly IJsonRpcClient m_client; @@ -32,6 +30,7 @@ namespace DispatchProxyJsonRpcClientConsoleApp { this.m_client = CreateJsonRpcClientByTcp(); } + public override IJsonRpcClient GetClient() { return this.m_client; @@ -50,7 +49,7 @@ namespace DispatchProxyJsonRpcClientConsoleApp } } - interface IJsonRpcServer + internal interface IJsonRpcServer { [JsonRpc(MethodInvoke = true)] string TestJsonRpc(string str); diff --git a/examples/JsonRpc/JsonRpcClientConsoleApp/Program.cs b/examples/JsonRpc/JsonRpcClientConsoleApp/Program.cs index e70476ced..b70c29672 100644 --- a/examples/JsonRpc/JsonRpcClientConsoleApp/Program.cs +++ b/examples/JsonRpc/JsonRpcClientConsoleApp/Program.cs @@ -2,14 +2,13 @@ using Newtonsoft.Json.Linq; using TouchSocket.Core; using TouchSocket.JsonRpc; -using TouchSocket.Rpc; using TouchSocket.Sockets; namespace JsonRpcClientConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var consoleAction = new ConsoleAction(); consoleAction.OnException += ConsoleAction_OnException; diff --git a/examples/JsonRpc/JsonRpcConsoleApp/JsonRpcProxy.cs b/examples/JsonRpc/JsonRpcConsoleApp/JsonRpcProxy.cs index 5fe1da270..2582fc96b 100644 --- a/examples/JsonRpc/JsonRpcConsoleApp/JsonRpcProxy.cs +++ b/examples/JsonRpc/JsonRpcConsoleApp/JsonRpcProxy.cs @@ -2,288 +2,311 @@ 此代码由Rpc工具直接生成,非必要请不要修改此处代码 */ #pragma warning disable + using System; -using TouchSocket.Core; -using TouchSocket.Sockets; -using TouchSocket.Rpc; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading.Tasks; +using TouchSocket.Core; +using TouchSocket.Rpc; +using TouchSocket.Sockets; + namespace JsonRpcProxy { -public interface IJsonRpcServer:TouchSocket.Rpc.IRemoteServer -{ -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -System.String TestGetContext(System.String str,IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task TestGetContextAsync(System.String str,IInvokeOption invokeOption = default); + public interface IJsonRpcServer : TouchSocket.Rpc.IRemoteServer + { + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + System.String TestGetContext(System.String str, IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Newtonsoft.Json.Linq.JObject TestJObject(Newtonsoft.Json.Linq.JObject obj,IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task TestJObjectAsync(Newtonsoft.Json.Linq.JObject obj,IInvokeOption invokeOption = default); + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task TestGetContextAsync(System.String str, IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -System.String TestJsonRpc(System.String str,IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task TestJsonRpcAsync(System.String str,IInvokeOption invokeOption = default); + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Newtonsoft.Json.Linq.JObject TestJObject(Newtonsoft.Json.Linq.JObject obj, IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -System.String Show(System.Int32 a,System.Int32 b,System.Int32 c,IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task ShowAsync(System.Int32 a,System.Int32 b,System.Int32 c,IInvokeOption invokeOption = default); + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task TestJObjectAsync(Newtonsoft.Json.Linq.JObject obj, IInvokeOption invokeOption = default); -} -public class JsonRpcServer :IJsonRpcServer -{ -public JsonRpcServer(IRpcClient client) -{ -this.Client=client; -} -public IRpcClient Client{get;private set; } -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public System.String TestGetContext(System.String str,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{str}; -System.String returnData=(System.String)Client.Invoke(typeof(System.String),"TestGetContext",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public async Task TestGetContextAsync(System.String str,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{str}; -return (System.String) await Client.InvokeAsync(typeof(System.String),"TestGetContext",invokeOption, parameters); -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + System.String TestJsonRpc(System.String str, IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public Newtonsoft.Json.Linq.JObject TestJObject(Newtonsoft.Json.Linq.JObject obj,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{obj}; -Newtonsoft.Json.Linq.JObject returnData=(Newtonsoft.Json.Linq.JObject)Client.Invoke(typeof(Newtonsoft.Json.Linq.JObject),"TestJObject",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public async Task TestJObjectAsync(Newtonsoft.Json.Linq.JObject obj,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{obj}; -return (Newtonsoft.Json.Linq.JObject) await Client.InvokeAsync(typeof(Newtonsoft.Json.Linq.JObject),"TestJObject",invokeOption, parameters); -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task TestJsonRpcAsync(System.String str, IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public System.String TestJsonRpc(System.String str,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{str}; -System.String returnData=(System.String)Client.Invoke(typeof(System.String),"TestJsonRpc",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public async Task TestJsonRpcAsync(System.String str,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{str}; -return (System.String) await Client.InvokeAsync(typeof(System.String),"TestJsonRpc",invokeOption, parameters); -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + System.String Show(System.Int32 a, System.Int32 b, System.Int32 c, IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public System.String Show(System.Int32 a,System.Int32 b,System.Int32 c,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{a,b,c}; -System.String returnData=(System.String)Client.Invoke(typeof(System.String),"Show",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public async Task ShowAsync(System.Int32 a,System.Int32 b,System.Int32 c,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{a,b,c}; -return (System.String) await Client.InvokeAsync(typeof(System.String),"Show",invokeOption, parameters); -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task ShowAsync(System.Int32 a, System.Int32 b, System.Int32 c, IInvokeOption invokeOption = default); + } -} -public static class JsonRpcServerExtensions -{ -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static System.String TestGetContext(this TClient client,System.String str,IInvokeOption invokeOption = default) where TClient: -TouchSocket.JsonRpc.IJsonRpcClient{ -object[] parameters = new object[]{str}; -System.String returnData=(System.String)client.Invoke(typeof(System.String),"TestGetContext",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public static async Task TestGetContextAsync(this TClient client,System.String str,IInvokeOption invokeOption = default) where TClient: -TouchSocket.JsonRpc.IJsonRpcClient{ -object[] parameters = new object[]{str}; -return (System.String) await client.InvokeAsync(typeof(System.String),"TestGetContext",invokeOption, parameters); -} + public class JsonRpcServer : IJsonRpcServer + { + public JsonRpcServer(IRpcClient client) + { + this.Client = client; + } -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static Newtonsoft.Json.Linq.JObject TestJObject(this TClient client,Newtonsoft.Json.Linq.JObject obj,IInvokeOption invokeOption = default) where TClient: -TouchSocket.JsonRpc.IJsonRpcClient{ -object[] parameters = new object[]{obj}; -Newtonsoft.Json.Linq.JObject returnData=(Newtonsoft.Json.Linq.JObject)client.Invoke(typeof(Newtonsoft.Json.Linq.JObject),"TestJObject",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public static async Task TestJObjectAsync(this TClient client,Newtonsoft.Json.Linq.JObject obj,IInvokeOption invokeOption = default) where TClient: -TouchSocket.JsonRpc.IJsonRpcClient{ -object[] parameters = new object[]{obj}; -return (Newtonsoft.Json.Linq.JObject) await client.InvokeAsync(typeof(Newtonsoft.Json.Linq.JObject),"TestJObject",invokeOption, parameters); -} + public IRpcClient Client { get; private set; } -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static System.String TestJsonRpc(this TClient client,System.String str,IInvokeOption invokeOption = default) where TClient: -TouchSocket.JsonRpc.IJsonRpcClient{ -object[] parameters = new object[]{str}; -System.String returnData=(System.String)client.Invoke(typeof(System.String),"TestJsonRpc",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public static async Task TestJsonRpcAsync(this TClient client,System.String str,IInvokeOption invokeOption = default) where TClient: -TouchSocket.JsonRpc.IJsonRpcClient{ -object[] parameters = new object[]{str}; -return (System.String) await client.InvokeAsync(typeof(System.String),"TestJsonRpc",invokeOption, parameters); -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public System.String TestGetContext(System.String str, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { str }; + System.String returnData = (System.String)Client.Invoke(typeof(System.String), "TestGetContext", invokeOption, parameters); + return returnData; + } -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static System.String Show(this TClient client,System.Int32 a,System.Int32 b,System.Int32 c,IInvokeOption invokeOption = default) where TClient: -TouchSocket.JsonRpc.IJsonRpcClient{ -object[] parameters = new object[]{a,b,c}; -System.String returnData=(System.String)client.Invoke(typeof(System.String),"Show",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public static async Task ShowAsync(this TClient client,System.Int32 a,System.Int32 b,System.Int32 c,IInvokeOption invokeOption = default) where TClient: -TouchSocket.JsonRpc.IJsonRpcClient{ -object[] parameters = new object[]{a,b,c}; -return (System.String) await client.InvokeAsync(typeof(System.String),"Show",invokeOption, parameters); -} + /// + ///无注释信息 + /// + public async Task TestGetContextAsync(System.String str, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { str }; + return (System.String)await Client.InvokeAsync(typeof(System.String), "TestGetContext", invokeOption, parameters); + } -} -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public Newtonsoft.Json.Linq.JObject TestJObject(Newtonsoft.Json.Linq.JObject obj, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { obj }; + Newtonsoft.Json.Linq.JObject returnData = (Newtonsoft.Json.Linq.JObject)Client.Invoke(typeof(Newtonsoft.Json.Linq.JObject), "TestJObject", invokeOption, parameters); + return returnData; + } + + /// + ///无注释信息 + /// + public async Task TestJObjectAsync(Newtonsoft.Json.Linq.JObject obj, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { obj }; + return (Newtonsoft.Json.Linq.JObject)await Client.InvokeAsync(typeof(Newtonsoft.Json.Linq.JObject), "TestJObject", invokeOption, parameters); + } + + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public System.String TestJsonRpc(System.String str, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { str }; + System.String returnData = (System.String)Client.Invoke(typeof(System.String), "TestJsonRpc", invokeOption, parameters); + return returnData; + } + + /// + ///无注释信息 + /// + public async Task TestJsonRpcAsync(System.String str, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { str }; + return (System.String)await Client.InvokeAsync(typeof(System.String), "TestJsonRpc", invokeOption, parameters); + } + + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public System.String Show(System.Int32 a, System.Int32 b, System.Int32 c, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { a, b, c }; + System.String returnData = (System.String)Client.Invoke(typeof(System.String), "Show", invokeOption, parameters); + return returnData; + } + + /// + ///无注释信息 + /// + public async Task ShowAsync(System.Int32 a, System.Int32 b, System.Int32 c, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { a, b, c }; + return (System.String)await Client.InvokeAsync(typeof(System.String), "Show", invokeOption, parameters); + } + } + + public static class JsonRpcServerExtensions + { + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static System.String TestGetContext(this TClient client, System.String str, IInvokeOption invokeOption = default) where TClient : + TouchSocket.JsonRpc.IJsonRpcClient + { + object[] parameters = new object[] { str }; + System.String returnData = (System.String)client.Invoke(typeof(System.String), "TestGetContext", invokeOption, parameters); + return returnData; + } + + /// + ///无注释信息 + /// + public static async Task TestGetContextAsync(this TClient client, System.String str, IInvokeOption invokeOption = default) where TClient : + TouchSocket.JsonRpc.IJsonRpcClient + { + object[] parameters = new object[] { str }; + return (System.String)await client.InvokeAsync(typeof(System.String), "TestGetContext", invokeOption, parameters); + } + + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static Newtonsoft.Json.Linq.JObject TestJObject(this TClient client, Newtonsoft.Json.Linq.JObject obj, IInvokeOption invokeOption = default) where TClient : + TouchSocket.JsonRpc.IJsonRpcClient + { + object[] parameters = new object[] { obj }; + Newtonsoft.Json.Linq.JObject returnData = (Newtonsoft.Json.Linq.JObject)client.Invoke(typeof(Newtonsoft.Json.Linq.JObject), "TestJObject", invokeOption, parameters); + return returnData; + } + + /// + ///无注释信息 + /// + public static async Task TestJObjectAsync(this TClient client, Newtonsoft.Json.Linq.JObject obj, IInvokeOption invokeOption = default) where TClient : + TouchSocket.JsonRpc.IJsonRpcClient + { + object[] parameters = new object[] { obj }; + return (Newtonsoft.Json.Linq.JObject)await client.InvokeAsync(typeof(Newtonsoft.Json.Linq.JObject), "TestJObject", invokeOption, parameters); + } + + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static System.String TestJsonRpc(this TClient client, System.String str, IInvokeOption invokeOption = default) where TClient : + TouchSocket.JsonRpc.IJsonRpcClient + { + object[] parameters = new object[] { str }; + System.String returnData = (System.String)client.Invoke(typeof(System.String), "TestJsonRpc", invokeOption, parameters); + return returnData; + } + + /// + ///无注释信息 + /// + public static async Task TestJsonRpcAsync(this TClient client, System.String str, IInvokeOption invokeOption = default) where TClient : + TouchSocket.JsonRpc.IJsonRpcClient + { + object[] parameters = new object[] { str }; + return (System.String)await client.InvokeAsync(typeof(System.String), "TestJsonRpc", invokeOption, parameters); + } + + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static System.String Show(this TClient client, System.Int32 a, System.Int32 b, System.Int32 c, IInvokeOption invokeOption = default) where TClient : + TouchSocket.JsonRpc.IJsonRpcClient + { + object[] parameters = new object[] { a, b, c }; + System.String returnData = (System.String)client.Invoke(typeof(System.String), "Show", invokeOption, parameters); + return returnData; + } + + /// + ///无注释信息 + /// + public static async Task ShowAsync(this TClient client, System.Int32 a, System.Int32 b, System.Int32 c, IInvokeOption invokeOption = default) where TClient : + TouchSocket.JsonRpc.IJsonRpcClient + { + object[] parameters = new object[] { a, b, c }; + return (System.String)await client.InvokeAsync(typeof(System.String), "Show", invokeOption, parameters); + } + } +} \ No newline at end of file diff --git a/examples/JsonRpc/JsonRpcConsoleApp/Program.cs b/examples/JsonRpc/JsonRpcConsoleApp/Program.cs index 08b36a5c4..eba989cde 100644 --- a/examples/JsonRpc/JsonRpcConsoleApp/Program.cs +++ b/examples/JsonRpc/JsonRpcConsoleApp/Program.cs @@ -40,7 +40,7 @@ namespace JsonRpcConsoleApp service.Setup(new TouchSocketConfig() .SetListenIPHosts(7706) - .ConfigureContainer(a => + .ConfigureContainer(a => { a.AddRpcStore(store => { @@ -63,7 +63,7 @@ namespace JsonRpcConsoleApp service.Setup(new TouchSocketConfig() .SetListenIPHosts(7707) - .ConfigureContainer(a => + .ConfigureContainer(a => { a.AddRpcStore(store => { @@ -94,7 +94,7 @@ namespace JsonRpcConsoleApp service.Setup(new TouchSocketConfig() .SetTcpDataHandlingAdapter(() => new TerminatorPackageAdapter("\r\n")) .SetListenIPHosts(7705) - .ConfigureContainer(a => + .ConfigureContainer(a => { a.AddRpcStore(store => { @@ -112,8 +112,6 @@ namespace JsonRpcConsoleApp })); service.Start(); } - - } public partial class JsonRpcServer : RpcServer diff --git a/examples/JsonRpc/ReverseJsonRpcConsoleApp/Program.cs b/examples/JsonRpc/ReverseJsonRpcConsoleApp/Program.cs index c0e209a94..8499be1f8 100644 --- a/examples/JsonRpc/ReverseJsonRpcConsoleApp/Program.cs +++ b/examples/JsonRpc/ReverseJsonRpcConsoleApp/Program.cs @@ -1,6 +1,4 @@ -using Newtonsoft.Json.Linq; -using System.Diagnostics; -using TouchSocket.Core; +using TouchSocket.Core; using TouchSocket.Http; using TouchSocket.Http.WebSockets; using TouchSocket.JsonRpc; @@ -11,7 +9,7 @@ namespace ReverseJsonRpcConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var service = GetService(); var client = GetClient(); @@ -19,7 +17,7 @@ namespace ReverseJsonRpcConsoleApp Console.ReadKey(); } - static WebSocketJsonRpcClient GetClient() + private static WebSocketJsonRpcClient GetClient() { var jsonRpcClient = new WebSocketJsonRpcClient(); jsonRpcClient.Setup(new TouchSocketConfig() @@ -36,7 +34,7 @@ namespace ReverseJsonRpcConsoleApp return jsonRpcClient; } - static HttpService GetService() + private static HttpService GetService() { var service = new HttpService(); @@ -62,19 +60,18 @@ namespace ReverseJsonRpcConsoleApp } } - class MyPluginClass : PluginBase, IWebSocketHandshakedPlugin + internal class MyPluginClass : PluginBase, IWebSocketHandshakedPlugin { - public async Task OnWebSocketHandshaked(IHttpSocketClient client, HttpContextEventArgs e) + public async Task OnWebSocketHandshaked(IWebSocket client, HttpContextEventArgs e) { try { //获取JsonRpcActionClient,用于执行反向Rpc - var jsonRpcClient = client.GetJsonRpcActionClient(); + var jsonRpcClient = ((IHttpSocketClient)client.Client).GetJsonRpcActionClient(); var result = await jsonRpcClient.InvokeTAsync("Add", InvokeOption.WaitInvoke, 10, 20); Console.WriteLine(result); - //Stopwatch stopwatch = Stopwatch.StartNew(); //for (int i = 0; i < 10000; i++) //{ @@ -89,7 +86,6 @@ namespace ReverseJsonRpcConsoleApp Console.WriteLine(ex.Message); } - await e.InvokeNext(); } } diff --git a/examples/Modbus/ModbusMasterConsoleApp/Program.cs b/examples/Modbus/ModbusMasterConsoleApp/Program.cs index d06225498..d614c784f 100644 --- a/examples/Modbus/ModbusMasterConsoleApp/Program.cs +++ b/examples/Modbus/ModbusMasterConsoleApp/Program.cs @@ -7,7 +7,7 @@ namespace ModbusClientConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var client = GetModbusTcpMaster(); @@ -55,7 +55,6 @@ namespace ModbusClientConsoleApp Console.WriteLine(reader.ReadInt64(EndianType.LittleSwap)); Console.WriteLine(reader.ReadString()); Console.WriteLine(reader.ReadObject(SerializationType.Json).ToJsonString()); - } /// @@ -151,9 +150,9 @@ namespace ModbusClientConsoleApp } } - class MyClass + internal class MyClass { public int P1 { get; set; } public int P2 { get; set; } } -} +} \ No newline at end of file diff --git a/examples/Modbus/ModbusObjectConsoleApp/Program.cs b/examples/Modbus/ModbusObjectConsoleApp/Program.cs index b0c9a8552..5b39c22fc 100644 --- a/examples/Modbus/ModbusObjectConsoleApp/Program.cs +++ b/examples/Modbus/ModbusObjectConsoleApp/Program.cs @@ -6,7 +6,7 @@ namespace ModbusObjectConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { try { @@ -44,13 +44,13 @@ namespace ModbusObjectConsoleApp /// Tcp从站 /// /// - static ModbusTcpSlave CreateModbusTcpSlave() + private static ModbusTcpSlave CreateModbusTcpSlave() { var service = new ModbusTcpSlave(); service.Setup(new TouchSocketConfig() //监听端口 .SetListenIPHosts(7808) - .ConfigurePlugins(a => + .ConfigurePlugins(a => { a.AddModbusSlavePoint()//添加一个从站站点 .SetSlaveId(1)//设置站点号 @@ -83,9 +83,10 @@ namespace ModbusObjectConsoleApp } } - class MyModbusObject : ModbusObject + internal class MyModbusObject : ModbusObject { #region Coils + /// /// 声明一个来自线圈的bool属性。 /// @@ -111,9 +112,11 @@ namespace ModbusObjectConsoleApp get { return this.GetValueArray(); } set { this.SetValueArray(value); } } - #endregion + + #endregion Coils #region DiscreteInputs + /// /// 声明一个来自离散输入的bool属性。 /// @@ -137,9 +140,11 @@ namespace ModbusObjectConsoleApp { get { return this.GetValue(); } } - #endregion + + #endregion DiscreteInputs #region HoldingRegisters + /// /// 声明一个来自保持寄存器的short属性。 /// @@ -165,9 +170,11 @@ namespace ModbusObjectConsoleApp get { return this.GetValueArray(); } set { this.SetValueArray(value); } } - #endregion + + #endregion HoldingRegisters #region InputRegisters + /// /// 声明一个来自输入寄存器的short属性。 /// @@ -191,6 +198,7 @@ namespace ModbusObjectConsoleApp { get { return this.GetValueArray(); } } - #endregion + + #endregion InputRegisters } -} +} \ No newline at end of file diff --git a/examples/Modbus/ModbusSlaveConsoleApp/Program.cs b/examples/Modbus/ModbusSlaveConsoleApp/Program.cs index 6f6470ba3..3f2a6d17e 100644 --- a/examples/Modbus/ModbusSlaveConsoleApp/Program.cs +++ b/examples/Modbus/ModbusSlaveConsoleApp/Program.cs @@ -7,7 +7,7 @@ namespace ModbusSlaveConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { try { @@ -22,7 +22,7 @@ namespace ModbusSlaveConsoleApp Console.ReadKey(); } - static ModbusTcpSlave CreateModbusTcpSlave() + private static ModbusTcpSlave CreateModbusTcpSlave() { var service = new ModbusTcpSlave(); service.Setup(new TouchSocketConfig() @@ -61,7 +61,7 @@ namespace ModbusSlaveConsoleApp return service; } - static ModbusRtuOverTcpSlave CreateModbusRtuOverTcpSlave() + private static ModbusRtuOverTcpSlave CreateModbusRtuOverTcpSlave() { var service = new ModbusRtuOverTcpSlave(); service.Setup(new TouchSocketConfig() @@ -82,7 +82,7 @@ namespace ModbusSlaveConsoleApp return service; } - static ModbusUdpSlave CreateModbusUdpSlave() + private static ModbusUdpSlave CreateModbusUdpSlave() { var service = new ModbusUdpSlave(); service.Setup(new TouchSocketConfig() @@ -103,7 +103,7 @@ namespace ModbusSlaveConsoleApp return service; } - static ModbusRtuOverUdpSlave CreateModbusRtuOverUdpSlave() + private static ModbusRtuOverUdpSlave CreateModbusRtuOverUdpSlave() { var service = new ModbusRtuOverUdpSlave(); service.Setup(new TouchSocketConfig() @@ -124,7 +124,7 @@ namespace ModbusSlaveConsoleApp return service; } - static ModbusRtuSlave CreateModbusRtuSlave() + private static ModbusRtuSlave CreateModbusRtuSlave() { var service = new ModbusRtuSlave(); service.Setup(new TouchSocketConfig() @@ -154,7 +154,7 @@ namespace ModbusSlaveConsoleApp } } - class MyModbusSlavePlugin : PluginBase, IModbusSlaveExecutingPlugin, IModbusSlaveExecutedPlugin + internal class MyModbusSlavePlugin : PluginBase, IModbusSlaveExecutingPlugin, IModbusSlaveExecutedPlugin { public async Task OnModbusSlaveExecuted(IModbusSlavePoint sender, ModbusSlaveExecutedEventArgs e) { @@ -171,4 +171,4 @@ namespace ModbusSlaveConsoleApp await e.InvokeNext(); } } -} +} \ No newline at end of file diff --git a/examples/NamedPipe/NamedPipeClientConsoleApp/Program.cs b/examples/NamedPipe/NamedPipeClientConsoleApp/Program.cs index f21f098b1..6c34829b4 100644 --- a/examples/NamedPipe/NamedPipeClientConsoleApp/Program.cs +++ b/examples/NamedPipe/NamedPipeClientConsoleApp/Program.cs @@ -1,5 +1,4 @@ -using System.Net.Sockets; -using System.Text; +using System.Text; using TouchSocket.Core; using TouchSocket.NamedPipe; using TouchSocket.Sockets; @@ -8,7 +7,7 @@ namespace NamedPipeClientConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var client = CreateClient(); @@ -46,7 +45,6 @@ namespace NamedPipeClientConsoleApp .SetPipeName("touchsocketpipe")//管道名称 .ConfigurePlugins(a => { - }) .ConfigureContainer(a => { diff --git a/examples/NamedPipe/NamedPipeServiceConsoleApp/Program.cs b/examples/NamedPipe/NamedPipeServiceConsoleApp/Program.cs index aaf12aa36..8e03578b8 100644 --- a/examples/NamedPipe/NamedPipeServiceConsoleApp/Program.cs +++ b/examples/NamedPipe/NamedPipeServiceConsoleApp/Program.cs @@ -1,5 +1,4 @@ -using System.Text; -using TouchSocket.Core; +using TouchSocket.Core; using TouchSocket.NamedPipe; using TouchSocket.Sockets; @@ -7,8 +6,7 @@ namespace NamedPipeServiceConsoleApp { internal class Program { - - static void Main(string[] args) + private static void Main(string[] args) { var service = CreateService(); @@ -53,7 +51,7 @@ namespace NamedPipeServiceConsoleApp } } - class MyNamedPipePlugin : PluginBase, INamedPipeConnectedPlugin, INamedPipeDisconnectedPlugin, INamedPipeReceivedPlugin + internal class MyNamedPipePlugin : PluginBase, INamedPipeConnectedPlugin, INamedPipeDisconnectedPlugin, INamedPipeReceivedPlugin { private readonly ILog m_logger; @@ -64,19 +62,19 @@ namespace NamedPipeServiceConsoleApp public async Task OnNamedPipeConnected(INamedPipeClientBase client, ConnectedEventArgs e) { - m_logger.Info("Connected"); + this.m_logger.Info("Connected"); await e.InvokeNext(); } public async Task OnNamedPipeDisconnected(INamedPipeClientBase client, DisconnectEventArgs e) { - m_logger.Info("Disconnected"); + this.m_logger.Info("Disconnected"); await e.InvokeNext(); } public async Task OnNamedPipeReceived(INamedPipeClientBase client, ReceivedDataEventArgs e) { - m_logger.Info(e.ByteBlock.ToString()); + this.m_logger.Info(e.ByteBlock.ToString()); client.Send(e.ByteBlock); await e.InvokeNext(); } diff --git a/examples/NamedPipe/NamedPipeStressTestingConsoleApp/Program.cs b/examples/NamedPipe/NamedPipeStressTestingConsoleApp/Program.cs index 3d13d6058..7f917959e 100644 --- a/examples/NamedPipe/NamedPipeStressTestingConsoleApp/Program.cs +++ b/examples/NamedPipe/NamedPipeStressTestingConsoleApp/Program.cs @@ -1,5 +1,4 @@ -using System.Text; -using TouchSocket.Core; +using TouchSocket.Core; using TouchSocket.NamedPipe; using TouchSocket.Sockets; @@ -7,7 +6,7 @@ namespace NamedPipeStressTestingConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { Console.WriteLine("请输入管道名称"); var name = Console.ReadLine(); @@ -15,9 +14,7 @@ namespace NamedPipeStressTestingConsoleApp var service = CreateService(name); var client = CreateClient(name); - - - byte[] buffer = new byte[1024 * 1024]; + var buffer = new byte[1024 * 1024]; while (true) { client.Send(buffer); @@ -33,7 +30,6 @@ namespace NamedPipeStressTestingConsoleApp .SetPipeName(name)//管道名称 .ConfigurePlugins(a => { - }) .ConfigureContainer(a => { @@ -52,7 +48,7 @@ namespace NamedPipeStressTestingConsoleApp service.Disconnected = (client, e) => { return EasyTask.CompletedTask; };//有客户端断开连接\ long count = 0; - DateTime dateTime = DateTime.Now; + var dateTime = DateTime.Now; service.Received = (client, e) => { if (DateTime.Now - dateTime > TimeSpan.FromSeconds(1)) diff --git a/examples/Rpc/GenerateProxyFromServerConsoleApp/Program.cs b/examples/Rpc/GenerateProxyFromServerConsoleApp/Program.cs index 6bceb89ea..44e6c0e4b 100644 --- a/examples/Rpc/GenerateProxyFromServerConsoleApp/Program.cs +++ b/examples/Rpc/GenerateProxyFromServerConsoleApp/Program.cs @@ -4,7 +4,7 @@ namespace GenerateProxyFromServerConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var rpcStore = new RpcStore(new TouchSocket.Core.Container()); @@ -12,7 +12,7 @@ namespace GenerateProxyFromServerConsoleApp } } - partial class MyRpcClass : RpcServer + internal partial class MyRpcClass : RpcServer { public int Add(int a, int b) { @@ -20,12 +20,13 @@ namespace GenerateProxyFromServerConsoleApp } } - class MyRpcAttribute : RpcAttribute + internal class MyRpcAttribute : RpcAttribute { public MyRpcAttribute() { this.GeneratorFlag = CodeGeneratorFlag.ExtensionAsync | CodeGeneratorFlag.InstanceAsync; } + public override Type[] GetGenericConstraintTypes() { return new Type[] { typeof(IRpcClient) }; diff --git a/examples/Rpc/RpcRateLimitingConsoleApp/Program.cs b/examples/Rpc/RpcRateLimitingConsoleApp/Program.cs index a7185e879..e09c164f9 100644 --- a/examples/Rpc/RpcRateLimitingConsoleApp/Program.cs +++ b/examples/Rpc/RpcRateLimitingConsoleApp/Program.cs @@ -11,7 +11,7 @@ namespace RpcRateLimitingConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var service = new TcpDmtpService(); var config = new TouchSocketConfig()//配置 @@ -25,7 +25,6 @@ namespace RpcRateLimitingConsoleApp store.RegisterServer();//注册服务 }); - a.AddRateLimiter(p => { //添加一个名称为FixedWindow的固定窗口的限流策略 @@ -36,7 +35,7 @@ namespace RpcRateLimitingConsoleApp }); //添加一个名称为SlidingWindow的滑动窗口的限流策略 - p.AddSlidingWindowLimiter("SlidingWindow", options => + p.AddSlidingWindowLimiter("SlidingWindow", options => { options.PermitLimit = 10; options.Window = TimeSpan.FromSeconds(10); @@ -96,4 +95,4 @@ namespace RpcRateLimitingConsoleApp return false; } } -} +} \ No newline at end of file diff --git a/examples/Serial/SerialPortClientConsoleApp/Program.cs b/examples/Serial/SerialPortClientConsoleApp/Program.cs index 67108e582..b6348b2f9 100644 --- a/examples/Serial/SerialPortClientConsoleApp/Program.cs +++ b/examples/Serial/SerialPortClientConsoleApp/Program.cs @@ -7,7 +7,7 @@ namespace SerialPortClientConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var client = new SerialPortClient(); client.Connecting = (client, e) => { return EasyTask.CompletedTask; };//即将连接到端口 @@ -28,7 +28,7 @@ namespace SerialPortClientConsoleApp PortName = "COM1",//COM StopBits = System.IO.Ports.StopBits.One//停止位 }) - .SetSerialDataHandlingAdapter(()=>new PeriodPackageAdapter()) + .SetSerialDataHandlingAdapter(() => new PeriodPackageAdapter()) .ConfigurePlugins(a => { a.Add(); @@ -61,7 +61,7 @@ namespace SerialPortClientConsoleApp } } - class MyClassPlugin : PluginBase, ISerialConnectedPlugin + internal class MyClassPlugin : PluginBase, ISerialConnectedPlugin { public async Task OnSerialConnected(ISerialPortClient client, ConnectedEventArgs e) { @@ -75,12 +75,12 @@ namespace SerialPortClientConsoleApp { //这里处理数据接收 //根据适配器类型,e.ByteBlock与e.RequestInfo会呈现不同的值,具体看文档=》适配器部分。 - ByteBlock byteBlock = e.ByteBlock; - IRequestInfo requestInfo = e.RequestInfo; + var byteBlock = e.ByteBlock; + var requestInfo = e.RequestInfo; //e.Handled = true;//表示该数据已经被本插件处理,无需再投递到其他插件。 await e.InvokeNext(); } } -} +} \ No newline at end of file diff --git a/examples/Tcp/ReuseAddressServerConsoleApp/Program.cs b/examples/Tcp/ReuseAddressServerConsoleApp/Program.cs index 736637bfe..2b680e9bc 100644 --- a/examples/Tcp/ReuseAddressServerConsoleApp/Program.cs +++ b/examples/Tcp/ReuseAddressServerConsoleApp/Program.cs @@ -5,7 +5,7 @@ namespace ReuseAddressServerConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var service = new TcpService(); service.Setup(new TouchSocketConfig()//载入配置 @@ -29,7 +29,7 @@ namespace ReuseAddressServerConsoleApp } } - class MyClassPlugin : PluginBase, ITcpConnectedPlugin,ITcpDisconnectedPlugin,ITcpReceivedPlugin + internal class MyClassPlugin : PluginBase, ITcpConnectedPlugin, ITcpDisconnectedPlugin, ITcpReceivedPlugin { private readonly ILog m_logger; @@ -37,6 +37,7 @@ namespace ReuseAddressServerConsoleApp { this.m_logger = logger; } + public async Task OnTcpConnected(ISocketClient client, ConnectedEventArgs e) { this.m_logger.Info($"已连接,信息:{client.GetInfo()}"); @@ -55,4 +56,4 @@ namespace ReuseAddressServerConsoleApp await e.InvokeNext(); } } -} +} \ No newline at end of file diff --git a/examples/Tcp/TcpCommandLineConsoleApp/Program.cs b/examples/Tcp/TcpCommandLineConsoleApp/Program.cs index ff6026e97..4370efc97 100644 --- a/examples/Tcp/TcpCommandLineConsoleApp/Program.cs +++ b/examples/Tcp/TcpCommandLineConsoleApp/Program.cs @@ -23,7 +23,7 @@ namespace TcpCommandLineConsoleApp .ConfigurePlugins(a => { a.UseCheckClear() - .SetCheckClearType( CheckClearType.All) + .SetCheckClearType(CheckClearType.All) .SetTick(TimeSpan.FromSeconds(60)); a.Add(); diff --git a/examples/Tcp/TcpConsoleApp/Program.cs b/examples/Tcp/TcpConsoleApp/Program.cs index 86ee41fa6..a13c0e648 100644 --- a/examples/Tcp/TcpConsoleApp/Program.cs +++ b/examples/Tcp/TcpConsoleApp/Program.cs @@ -21,7 +21,6 @@ namespace ServiceConsoleApp consoleAction.RunCommandLine(); } - private static TcpService CreateService() { var service = new TcpService(); @@ -50,7 +49,6 @@ namespace ServiceConsoleApp return service; } - /// /// 以Received异步委托接收数据 /// @@ -122,28 +120,25 @@ namespace ServiceConsoleApp client.Logger.Info($"客户端接收到信息:{mes}"); //如果是适配器信息,则可以直接获取receiverResult.RequestInfo; - } } } } } - class MyTcpClient : TcpClientBase + internal class MyTcpClient : TcpClientBase { protected override async Task ReceivedData(ReceivedDataEventArgs e) { //此处逻辑单线程处理。 //此处处理数据,功能相当于Received委托。 - string mes = Encoding.UTF8.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len); + var mes = Encoding.UTF8.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len); Console.WriteLine($"已接收到信息:{mes}"); await base.ReceivedData(e); } } - - internal class MyServicePluginClass : PluginBase, IServerStartedPlugin, IServerStopedPlugin { public Task OnServerStarted(IService sender, ServiceStateEventArgs e) @@ -173,7 +168,7 @@ namespace ServiceConsoleApp } } - class TcpServiceReceiveAsyncPlugin : PluginBase, ITcpConnectedPlugin + internal class TcpServiceReceiveAsyncPlugin : PluginBase, ITcpConnectedPlugin { public async Task OnTcpConnected(ISocketClient client, ConnectedEventArgs e) { @@ -195,14 +190,13 @@ namespace ServiceConsoleApp client.Logger.Info($"客户端接收到信息:{mes}"); //如果是适配器信息,则可以直接获取receiverResult.RequestInfo; - } } } } } - class TcpServiceReceivedPlugin : PluginBase, ITcpReceivedPlugin + internal class TcpServiceReceivedPlugin : PluginBase, ITcpReceivedPlugin { public async Task OnTcpReceived(ISocketClient client, ReceivedDataEventArgs e) { @@ -235,7 +229,7 @@ namespace ServiceConsoleApp /// /// 应一个网友要求,该插件主要实现,在接收数据时如果触发异常,则断开连接。 /// - class ClosePlugin : PluginBase, ITcpReceivedPlugin + internal class ClosePlugin : PluginBase, ITcpReceivedPlugin { private readonly ILog m_logger; @@ -252,22 +246,22 @@ namespace ServiceConsoleApp } catch (CloseException ex) { - m_logger.Info("拦截到CloseException"); + this.m_logger.Info("拦截到CloseException"); client.Close(ex.Message); } catch (Exception exx) { - } finally { - } } } - class CloseException : Exception + internal class CloseException : Exception { - public CloseException(string msg) : base(msg) { } + public CloseException(string msg) : base(msg) + { + } } } \ No newline at end of file diff --git a/examples/Tcp/TcpWaitingClientWinFormsApp/Form1.cs b/examples/Tcp/TcpWaitingClientWinFormsApp/Form1.cs index d01d92f31..55bec8017 100644 --- a/examples/Tcp/TcpWaitingClientWinFormsApp/Form1.cs +++ b/examples/Tcp/TcpWaitingClientWinFormsApp/Form1.cs @@ -11,7 +11,7 @@ namespace TcpWaitingClientWinFormsApp this.InitializeComponent(); } - TcpClient m_tcpClient; + private TcpClient m_tcpClient; private void IsConnected() { diff --git a/examples/Tcp/TcpWaitingClientWinFormsApp/Program.cs b/examples/Tcp/TcpWaitingClientWinFormsApp/Program.cs index 61c7df2e4..0543344a1 100644 --- a/examples/Tcp/TcpWaitingClientWinFormsApp/Program.cs +++ b/examples/Tcp/TcpWaitingClientWinFormsApp/Program.cs @@ -9,7 +9,7 @@ namespace TcpWaitingClientWinFormsApp /// The main entry point for the application. /// [STAThread] - static void Main() + private static void Main() { CreateService(); // To customize application configuration such as set high DPI settings or default font, @@ -18,7 +18,7 @@ namespace TcpWaitingClientWinFormsApp Application.Run(new Form1()); } - static void CreateService() + private static void CreateService() { var service = new TcpService(); @@ -37,7 +37,7 @@ namespace TcpWaitingClientWinFormsApp service.Logger.Info(""); } - class MyPlugin1 : PluginBase, ITcpReceivedPlugin + private class MyPlugin1 : PluginBase, ITcpReceivedPlugin { private readonly ILog m_logger; @@ -45,6 +45,7 @@ namespace TcpWaitingClientWinFormsApp { this.m_logger = logger; } + public async Task OnTcpReceived(ITcpClientBase client, ReceivedDataEventArgs e) { this.m_logger.Info($"յݣ{e.ByteBlock.ToString()}"); diff --git a/examples/Udp/UdpBroadcastConsoleApp/Program.cs b/examples/Udp/UdpBroadcastConsoleApp/Program.cs index c000df8ff..b66729260 100644 --- a/examples/Udp/UdpBroadcastConsoleApp/Program.cs +++ b/examples/Udp/UdpBroadcastConsoleApp/Program.cs @@ -45,7 +45,7 @@ namespace UdpBroadcastConsoleApp } } - class MyPluginClass1 : PluginBase, IUdpReceivedPlugin + private class MyPluginClass1 : PluginBase, IUdpReceivedPlugin { public async Task OnUdpReceived(IUdpSession client, UdpReceivedDataEventArgs e) { @@ -62,7 +62,7 @@ namespace UdpBroadcastConsoleApp } } - class MyPluginClass2 : PluginBase, IUdpReceivedPlugin + private class MyPluginClass2 : PluginBase, IUdpReceivedPlugin { public async Task OnUdpReceived(IUdpSession client, UdpReceivedDataEventArgs e) { @@ -79,7 +79,7 @@ namespace UdpBroadcastConsoleApp } } - class MyPluginClass3 : PluginBase, IUdpReceivedPlugin + private class MyPluginClass3 : PluginBase, IUdpReceivedPlugin { public async Task OnUdpReceived(IUdpSession client, UdpReceivedDataEventArgs e) { diff --git a/examples/Udp/UdpDemoApp/Form1.cs b/examples/Udp/UdpDemoApp/Form1.cs index 7ea502945..118dd9a67 100644 --- a/examples/Udp/UdpDemoApp/Form1.cs +++ b/examples/Udp/UdpDemoApp/Form1.cs @@ -51,7 +51,7 @@ namespace UdpDemoApp { a.SetSingletonLogger(new LoggerGroup(new EasyLogger(this.ShowMsg), new FileLogger())); })); - m_udpSession.Start(); + this.m_udpSession.Start(); this.m_udpSession.Logger.Info("等待接收"); } diff --git a/examples/Udp/UdpScreenCapture/ScreenUdpReceiver/Form1.cs b/examples/Udp/UdpScreenCapture/ScreenUdpReceiver/Form1.cs index 2bbcd3282..92c9f72d6 100644 --- a/examples/Udp/UdpScreenCapture/ScreenUdpReceiver/Form1.cs +++ b/examples/Udp/UdpScreenCapture/ScreenUdpReceiver/Form1.cs @@ -32,7 +32,7 @@ namespace ScreenUdpReceiver this.udpSession.Setup(new TouchSocketConfig() .SetBindIPHost(new IPHost("127.0.0.1:7790")) .SetUdpDataHandlingAdapter(() => { return new UdpPackageAdapter() { MaxPackageSize = 1024 * 1024, MTU = 1024 * 10 }; })); - udpSession.Start(); + this.udpSession.Start(); } catch (Exception ex) { diff --git a/examples/Udp/UdpScreenCapture/ScreenUdpSender/Form1.cs b/examples/Udp/UdpScreenCapture/ScreenUdpSender/Form1.cs index 209fc2c17..072b3a324 100644 --- a/examples/Udp/UdpScreenCapture/ScreenUdpSender/Form1.cs +++ b/examples/Udp/UdpScreenCapture/ScreenUdpSender/Form1.cs @@ -124,7 +124,7 @@ namespace ScreenUdpSender new TouchSocketConfig() .SetBindIPHost(new IPHost(7789)) .SetUdpDataHandlingAdapter(() => { return new UdpPackageAdapter() { MaxPackageSize = 1024 * 1024, MTU = 1024 * 10 }; })); - udpSession.Start(); + this.udpSession.Start(); this.m_thread = new Thread(this.Tick); this.m_thread.IsBackground = true; this.m_thread.Start(); diff --git a/examples/Unity3d/UnityServerConsoleApp/Program.cs b/examples/Unity3d/UnityServerConsoleApp/Program.cs index 1a81140f9..2a8bd48ff 100644 --- a/examples/Unity3d/UnityServerConsoleApp/Program.cs +++ b/examples/Unity3d/UnityServerConsoleApp/Program.cs @@ -61,7 +61,6 @@ namespace UnityServerConsoleApp var code = store.GetProxyCodes("UnityRpcProxy", typeof(DmtpRpcAttribute)); File.WriteAllText("../../../UnityRpcProxy.cs", code); #endif - }); }) .ConfigurePlugins(a => @@ -106,7 +105,6 @@ namespace UnityServerConsoleApp internal class MyPlguin : PluginBase, ITcpConnectedPlugin, ITcpDisconnectedPlugin, ITcpReceivedPlugin { - public async Task OnTcpConnected(ISocketClient client, ConnectedEventArgs e) { client.Logger.Info($"客户端{client.GetInfo()}已连接"); diff --git a/examples/Unity3d/UnityServerConsoleApp/UnityRpcProxy.cs b/examples/Unity3d/UnityServerConsoleApp/UnityRpcProxy.cs index ebfff1df9..c71e7a5c0 100644 --- a/examples/Unity3d/UnityServerConsoleApp/UnityRpcProxy.cs +++ b/examples/Unity3d/UnityServerConsoleApp/UnityRpcProxy.cs @@ -2,173 +2,184 @@ 此代码由Rpc工具直接生成,非必要请不要修改此处代码 */ #pragma warning disable + using System; -using TouchSocket.Core; -using TouchSocket.Sockets; -using TouchSocket.Rpc; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading.Tasks; +using TouchSocket.Core; +using TouchSocket.Rpc; +using TouchSocket.Sockets; + namespace UnityRpcProxy { -public interface IMyRpcServer:TouchSocket.Rpc.IRemoteServer -{ -/// -///登录 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -MyLoginModelResult Login(MyLoginModel model,IInvokeOption invokeOption = default); -/// -///登录 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task LoginAsync(MyLoginModel model,IInvokeOption invokeOption = default); + public interface IMyRpcServer : TouchSocket.Rpc.IRemoteServer + { + /// + ///登录 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + MyLoginModelResult Login(MyLoginModel model, IInvokeOption invokeOption = default); -/// -///性能测试 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -System.Int32 Performance(System.Int32 i,IInvokeOption invokeOption = default); -/// -///性能测试 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task PerformanceAsync(System.Int32 i,IInvokeOption invokeOption = default); + /// + ///登录 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task LoginAsync(MyLoginModel model, IInvokeOption invokeOption = default); -} -public class MyRpcServer :IMyRpcServer -{ -public MyRpcServer(IRpcClient client) -{ -this.Client=client; -} -public IRpcClient Client{get;private set; } -/// -///登录 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public MyLoginModelResult Login(MyLoginModel model,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{model}; -MyLoginModelResult returnData=(MyLoginModelResult)Client.Invoke(typeof(MyLoginModelResult),"Login",invokeOption, parameters); -return returnData; -} -/// -///登录 -/// -public async Task LoginAsync(MyLoginModel model,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{model}; -return (MyLoginModelResult) await Client.InvokeAsync(typeof(MyLoginModelResult),"Login",invokeOption, parameters); -} + /// + ///性能测试 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + System.Int32 Performance(System.Int32 i, IInvokeOption invokeOption = default); -/// -///性能测试 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public System.Int32 Performance(System.Int32 i,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{i}; -System.Int32 returnData=(System.Int32)Client.Invoke(typeof(System.Int32),"Performance",invokeOption, parameters); -return returnData; -} -/// -///性能测试 -/// -public async Task PerformanceAsync(System.Int32 i,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{i}; -return (System.Int32) await Client.InvokeAsync(typeof(System.Int32),"Performance",invokeOption, parameters); -} + /// + ///性能测试 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task PerformanceAsync(System.Int32 i, IInvokeOption invokeOption = default); + } -} -public static class MyRpcServerExtensions -{ -/// -///登录 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static MyLoginModelResult Login(this TClient client,MyLoginModel model,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -object[] parameters = new object[]{model}; -MyLoginModelResult returnData=(MyLoginModelResult)client.Invoke(typeof(MyLoginModelResult),"Login",invokeOption, parameters); -return returnData; -} -/// -///登录 -/// -public static async Task LoginAsync(this TClient client,MyLoginModel model,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -object[] parameters = new object[]{model}; -return (MyLoginModelResult) await client.InvokeAsync(typeof(MyLoginModelResult),"Login",invokeOption, parameters); -} + public class MyRpcServer : IMyRpcServer + { + public MyRpcServer(IRpcClient client) + { + this.Client = client; + } -/// -///性能测试 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static System.Int32 Performance(this TClient client,System.Int32 i,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -object[] parameters = new object[]{i}; -System.Int32 returnData=(System.Int32)client.Invoke(typeof(System.Int32),"Performance",invokeOption, parameters); -return returnData; -} -/// -///性能测试 -/// -public static async Task PerformanceAsync(this TClient client,System.Int32 i,IInvokeOption invokeOption = default) where TClient: -TouchSocket.Rpc.IRpcClient{ -object[] parameters = new object[]{i}; -return (System.Int32) await client.InvokeAsync(typeof(System.Int32),"Performance",invokeOption, parameters); -} + public IRpcClient Client { get; private set; } -} + /// + ///登录 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public MyLoginModelResult Login(MyLoginModel model, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { model }; + MyLoginModelResult returnData = (MyLoginModelResult)Client.Invoke(typeof(MyLoginModelResult), "Login", invokeOption, parameters); + return returnData; + } -public class MyLoginModelResult -{ -public System.Byte Status{get;set;} -public System.String Message{get;set;} -} + /// + ///登录 + /// + public async Task LoginAsync(MyLoginModel model, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { model }; + return (MyLoginModelResult)await Client.InvokeAsync(typeof(MyLoginModelResult), "Login", invokeOption, parameters); + } + /// + ///性能测试 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public System.Int32 Performance(System.Int32 i, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { i }; + System.Int32 returnData = (System.Int32)Client.Invoke(typeof(System.Int32), "Performance", invokeOption, parameters); + return returnData; + } -public class MyLoginModel -{ -public System.String Token{get;set;} -public System.String Account{get;set;} -public System.String Password{get;set;} -} + /// + ///性能测试 + /// + public async Task PerformanceAsync(System.Int32 i, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { i }; + return (System.Int32)await Client.InvokeAsync(typeof(System.Int32), "Performance", invokeOption, parameters); + } + } -} + public static class MyRpcServerExtensions + { + /// + ///登录 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static MyLoginModelResult Login(this TClient client, MyLoginModel model, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + object[] parameters = new object[] { model }; + MyLoginModelResult returnData = (MyLoginModelResult)client.Invoke(typeof(MyLoginModelResult), "Login", invokeOption, parameters); + return returnData; + } + + /// + ///登录 + /// + public static async Task LoginAsync(this TClient client, MyLoginModel model, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + object[] parameters = new object[] { model }; + return (MyLoginModelResult)await client.InvokeAsync(typeof(MyLoginModelResult), "Login", invokeOption, parameters); + } + + /// + ///性能测试 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static System.Int32 Performance(this TClient client, System.Int32 i, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + object[] parameters = new object[] { i }; + System.Int32 returnData = (System.Int32)client.Invoke(typeof(System.Int32), "Performance", invokeOption, parameters); + return returnData; + } + + /// + ///性能测试 + /// + public static async Task PerformanceAsync(this TClient client, System.Int32 i, IInvokeOption invokeOption = default) where TClient : + TouchSocket.Rpc.IRpcClient + { + object[] parameters = new object[] { i }; + return (System.Int32)await client.InvokeAsync(typeof(System.Int32), "Performance", invokeOption, parameters); + } + } + + public class MyLoginModelResult + { + public System.Byte Status { get; set; } + public System.String Message { get; set; } + } + + public class MyLoginModel + { + public System.String Token { get; set; } + public System.String Account { get; set; } + public System.String Password { get; set; } + } +} \ No newline at end of file diff --git a/examples/WebApi/DispatchProxyWebApiConsoleApp/Program.cs b/examples/WebApi/DispatchProxyWebApiConsoleApp/Program.cs index 2cb0c8796..f12834ea8 100644 --- a/examples/WebApi/DispatchProxyWebApiConsoleApp/Program.cs +++ b/examples/WebApi/DispatchProxyWebApiConsoleApp/Program.cs @@ -10,16 +10,16 @@ namespace DispatchProxyWebApiConsoleApp /// 使用DispatchProxy生成调用代理 /// /// - static void Main(string[] args) + private static void Main(string[] args) { var api = MyWebApiDispatchProxy.Create(); while (true) { Console.WriteLine("请输入两个数,中间用空格隔开,回车确认"); - string str = Console.ReadLine(); + var str = Console.ReadLine(); var strs = str.Split(' '); - int a = int.Parse(strs[0]); - int b = int.Parse(strs[1]); + var a = int.Parse(strs[0]); + var b = int.Parse(strs[1]); var sum = api.Sum(a, b); Console.WriteLine(sum); @@ -31,7 +31,7 @@ namespace DispatchProxyWebApiConsoleApp /// 新建一个类,继承WebApiDispatchProxy,亦或者RpcDispatchProxy基类。 /// 然后实现抽象方法,主要是能获取到调用的IRpcClient派生接口。 /// - class MyWebApiDispatchProxy : WebApiDispatchProxy + internal class MyWebApiDispatchProxy : WebApiDispatchProxy { private readonly WebApiClient m_client; @@ -56,11 +56,11 @@ namespace DispatchProxyWebApiConsoleApp public override IWebApiClientBase GetClient() { - return m_client; + return this.m_client; } } - interface IApiServer + internal interface IApiServer { [Router("ApiServer/[action]ab")] [Router("ApiServer/[action]")] diff --git a/examples/WebApi/WebApiClientApp/Program.cs b/examples/WebApi/WebApiClientApp/Program.cs index b9bd5b047..2b5a00d8b 100644 --- a/examples/WebApi/WebApiClientApp/Program.cs +++ b/examples/WebApi/WebApiClientApp/Program.cs @@ -45,7 +45,6 @@ namespace WebApiClientApp Console.WriteLine($"代理调用成功,结果:{sum3}"); } - Console.ReadKey(); } @@ -78,7 +77,7 @@ namespace WebApiClientApp /// /// 此处可以做WebApi的请求之前和之后的拦截。 /// - class MyWebApiPlugin : PluginBase, IWebApiPlugin + private class MyWebApiPlugin : PluginBase, IWebApiPlugin { public async Task OnRequest(IWebApiClientBase client, WebApiEventArgs e) { diff --git a/examples/WebApi/WebApiServer/Program.cs b/examples/WebApi/WebApiServer/Program.cs index 11fa3e201..c6ee264d6 100644 --- a/examples/WebApi/WebApiServer/Program.cs +++ b/examples/WebApi/WebApiServer/Program.cs @@ -176,12 +176,12 @@ namespace WebApiServerApp [WebApi(HttpMethodType.POST)] public Task UploadBigFile(IWebApiCallContext callContext) { - using (FileStream stream = File.Create("text.file")) + using (var stream = File.Create("text.file")) { - byte[] buffer = new byte[1024 * 64]; + var buffer = new byte[1024 * 64]; while (true) { - int r = callContext.HttpContext.Request.Read(buffer, 0, buffer.Length); + var r = callContext.HttpContext.Request.Read(buffer, 0, buffer.Length); if (r == 0) { @@ -207,7 +207,7 @@ namespace WebApiServerApp /// /// 鉴权插件 /// - class AuthenticationPlugin : PluginBase, IHttpPlugin + internal class AuthenticationPlugin : PluginBase, IHttpPlugin { public async Task OnHttpRequest(IHttpSocketClient client, HttpContextEventArgs e) { @@ -229,7 +229,7 @@ namespace WebApiServerApp } } - class MySerializerFormatter : ISerializerFormatter + internal class MySerializerFormatter : ISerializerFormatter { public int Order { get; set; } diff --git a/examples/WebApi/WebApiServer/WebApiProxy.cs b/examples/WebApi/WebApiServer/WebApiProxy.cs index f7f7b6a07..e03ae5cfa 100644 --- a/examples/WebApi/WebApiServer/WebApiProxy.cs +++ b/examples/WebApi/WebApiServer/WebApiProxy.cs @@ -2,477 +2,515 @@ 此代码由Rpc工具直接生成,非必要请不要修改此处代码 */ #pragma warning disable + using System; -using TouchSocket.Core; -using TouchSocket.Sockets; -using TouchSocket.Rpc; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading.Tasks; +using TouchSocket.Core; +using TouchSocket.Rpc; +using TouchSocket.Sockets; + namespace WebApiProxy { -public interface IApiServer:TouchSocket.Rpc.IRemoteServer -{ -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -System.Int32 Sum(System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task SumAsync(System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default); + public interface IApiServer : TouchSocket.Rpc.IRemoteServer + { + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + System.Int32 Sum(System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -MyClass GetMyClass(IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task GetMyClassAsync(IInvokeOption invokeOption = default); + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task SumAsync(System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -System.Int32 TestPost(MyClass myClass,IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task TestPostAsync(MyClass myClass,IInvokeOption invokeOption = default); + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + MyClass GetMyClass(IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -System.String DownloadFile(System.String id,IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task DownloadFileAsync(System.String id,IInvokeOption invokeOption = default); + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task GetMyClassAsync(IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -System.String PostContent(IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task PostContentAsync(IInvokeOption invokeOption = default); + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + System.Int32 TestPost(MyClass myClass, IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -System.String UploadMultiFile(System.String id,IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task UploadMultiFileAsync(System.String id,IInvokeOption invokeOption = default); + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task TestPostAsync(MyClass myClass, IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -System.String UploadBigFile(IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task UploadBigFileAsync(IInvokeOption invokeOption = default); + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + System.String DownloadFile(System.String id, IInvokeOption invokeOption = default); -} -public class ApiServer :IApiServer -{ -public ApiServer(IRpcClient client) -{ -this.Client=client; -} -public IRpcClient Client{get;private set; } -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public System.Int32 Sum(System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{a,b}; -System.Int32 returnData=(System.Int32)Client.Invoke(typeof(System.Int32),"GET:/apiserver/sumab?a={0}&b={1}",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public async Task SumAsync(System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{a,b}; -return (System.Int32) await Client.InvokeAsync(typeof(System.Int32),"GET:/apiserver/sumab?a={0}&b={1}",invokeOption, parameters); -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task DownloadFileAsync(System.String id, IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public MyClass GetMyClass(IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -MyClass returnData=(MyClass)Client.Invoke(typeof(MyClass),"GET:/apiserver/getmyclass",invokeOption, null); -return returnData; -} -/// -///无注释信息 -/// -public async Task GetMyClassAsync(IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -return (MyClass) await Client.InvokeAsync(typeof(MyClass),"GET:/apiserver/getmyclass",invokeOption, null); -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + System.String PostContent(IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public System.Int32 TestPost(MyClass myClass,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{myClass}; -System.Int32 returnData=(System.Int32)Client.Invoke(typeof(System.Int32),"POST:/apiserver/testpost?",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public async Task TestPostAsync(MyClass myClass,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{myClass}; -return (System.Int32) await Client.InvokeAsync(typeof(System.Int32),"POST:/apiserver/testpost?",invokeOption, parameters); -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task PostContentAsync(IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public System.String DownloadFile(System.String id,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{id}; -System.String returnData=(System.String)Client.Invoke(typeof(System.String),"GET:/apiserver/downloadfile?id={0}",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public async Task DownloadFileAsync(System.String id,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{id}; -return (System.String) await Client.InvokeAsync(typeof(System.String),"GET:/apiserver/downloadfile?id={0}",invokeOption, parameters); -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + System.String UploadMultiFile(System.String id, IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public System.String PostContent(IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -System.String returnData=(System.String)Client.Invoke(typeof(System.String),"POST:/apiserver/postcontent",invokeOption, null); -return returnData; -} -/// -///无注释信息 -/// -public async Task PostContentAsync(IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -return (System.String) await Client.InvokeAsync(typeof(System.String),"POST:/apiserver/postcontent",invokeOption, null); -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task UploadMultiFileAsync(System.String id, IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public System.String UploadMultiFile(System.String id,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{id}; -System.String returnData=(System.String)Client.Invoke(typeof(System.String),"POST:/apiserver/uploadmultifile?id={0}",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public async Task UploadMultiFileAsync(System.String id,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{id}; -return (System.String) await Client.InvokeAsync(typeof(System.String),"POST:/apiserver/uploadmultifile?id={0}",invokeOption, parameters); -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + System.String UploadBigFile(IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public System.String UploadBigFile(IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -System.String returnData=(System.String)Client.Invoke(typeof(System.String),"POST:/apiserver/uploadbigfile",invokeOption, null); -return returnData; -} -/// -///无注释信息 -/// -public async Task UploadBigFileAsync(IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -return (System.String) await Client.InvokeAsync(typeof(System.String),"POST:/apiserver/uploadbigfile",invokeOption, null); -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task UploadBigFileAsync(IInvokeOption invokeOption = default); + } -} -public static class ApiServerExtensions -{ -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static System.Int32 Sum(this TClient client,System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default) where TClient: -TouchSocket.WebApi.IWebApiClientBase{ -object[] parameters = new object[]{a,b}; -System.Int32 returnData=(System.Int32)client.Invoke(typeof(System.Int32),"GET:/apiserver/sumab?a={0}&b={1}",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public static async Task SumAsync(this TClient client,System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default) where TClient: -TouchSocket.WebApi.IWebApiClientBase{ -object[] parameters = new object[]{a,b}; -return (System.Int32) await client.InvokeAsync(typeof(System.Int32),"GET:/apiserver/sumab?a={0}&b={1}",invokeOption, parameters); -} + public class ApiServer : IApiServer + { + public ApiServer(IRpcClient client) + { + this.Client = client; + } -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static MyClass GetMyClass(this TClient client,IInvokeOption invokeOption = default) where TClient: -TouchSocket.WebApi.IWebApiClientBase{ -MyClass returnData=(MyClass)client.Invoke(typeof(MyClass),"GET:/apiserver/getmyclass",invokeOption, null); -return returnData; -} -/// -///无注释信息 -/// -public static async Task GetMyClassAsync(this TClient client,IInvokeOption invokeOption = default) where TClient: -TouchSocket.WebApi.IWebApiClientBase{ -return (MyClass) await client.InvokeAsync(typeof(MyClass),"GET:/apiserver/getmyclass",invokeOption, null); -} + public IRpcClient Client { get; private set; } -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static System.Int32 TestPost(this TClient client,MyClass myClass,IInvokeOption invokeOption = default) where TClient: -TouchSocket.WebApi.IWebApiClientBase{ -object[] parameters = new object[]{myClass}; -System.Int32 returnData=(System.Int32)client.Invoke(typeof(System.Int32),"POST:/apiserver/testpost?",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public static async Task TestPostAsync(this TClient client,MyClass myClass,IInvokeOption invokeOption = default) where TClient: -TouchSocket.WebApi.IWebApiClientBase{ -object[] parameters = new object[]{myClass}; -return (System.Int32) await client.InvokeAsync(typeof(System.Int32),"POST:/apiserver/testpost?",invokeOption, parameters); -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public System.Int32 Sum(System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { a, b }; + System.Int32 returnData = (System.Int32)Client.Invoke(typeof(System.Int32), "GET:/apiserver/sumab?a={0}&b={1}", invokeOption, parameters); + return returnData; + } -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static System.String DownloadFile(this TClient client,System.String id,IInvokeOption invokeOption = default) where TClient: -TouchSocket.WebApi.IWebApiClientBase{ -object[] parameters = new object[]{id}; -System.String returnData=(System.String)client.Invoke(typeof(System.String),"GET:/apiserver/downloadfile?id={0}",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public static async Task DownloadFileAsync(this TClient client,System.String id,IInvokeOption invokeOption = default) where TClient: -TouchSocket.WebApi.IWebApiClientBase{ -object[] parameters = new object[]{id}; -return (System.String) await client.InvokeAsync(typeof(System.String),"GET:/apiserver/downloadfile?id={0}",invokeOption, parameters); -} + /// + ///无注释信息 + /// + public async Task SumAsync(System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { a, b }; + return (System.Int32)await Client.InvokeAsync(typeof(System.Int32), "GET:/apiserver/sumab?a={0}&b={1}", invokeOption, parameters); + } -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static System.String PostContent(this TClient client,IInvokeOption invokeOption = default) where TClient: -TouchSocket.WebApi.IWebApiClientBase{ -System.String returnData=(System.String)client.Invoke(typeof(System.String),"POST:/apiserver/postcontent",invokeOption, null); -return returnData; -} -/// -///无注释信息 -/// -public static async Task PostContentAsync(this TClient client,IInvokeOption invokeOption = default) where TClient: -TouchSocket.WebApi.IWebApiClientBase{ -return (System.String) await client.InvokeAsync(typeof(System.String),"POST:/apiserver/postcontent",invokeOption, null); -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public MyClass GetMyClass(IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + MyClass returnData = (MyClass)Client.Invoke(typeof(MyClass), "GET:/apiserver/getmyclass", invokeOption, null); + return returnData; + } -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static System.String UploadMultiFile(this TClient client,System.String id,IInvokeOption invokeOption = default) where TClient: -TouchSocket.WebApi.IWebApiClientBase{ -object[] parameters = new object[]{id}; -System.String returnData=(System.String)client.Invoke(typeof(System.String),"POST:/apiserver/uploadmultifile?id={0}",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public static async Task UploadMultiFileAsync(this TClient client,System.String id,IInvokeOption invokeOption = default) where TClient: -TouchSocket.WebApi.IWebApiClientBase{ -object[] parameters = new object[]{id}; -return (System.String) await client.InvokeAsync(typeof(System.String),"POST:/apiserver/uploadmultifile?id={0}",invokeOption, parameters); -} + /// + ///无注释信息 + /// + public async Task GetMyClassAsync(IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + return (MyClass)await Client.InvokeAsync(typeof(MyClass), "GET:/apiserver/getmyclass", invokeOption, null); + } -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static System.String UploadBigFile(this TClient client,IInvokeOption invokeOption = default) where TClient: -TouchSocket.WebApi.IWebApiClientBase{ -System.String returnData=(System.String)client.Invoke(typeof(System.String),"POST:/apiserver/uploadbigfile",invokeOption, null); -return returnData; -} -/// -///无注释信息 -/// -public static async Task UploadBigFileAsync(this TClient client,IInvokeOption invokeOption = default) where TClient: -TouchSocket.WebApi.IWebApiClientBase{ -return (System.String) await client.InvokeAsync(typeof(System.String),"POST:/apiserver/uploadbigfile",invokeOption, null); -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public System.Int32 TestPost(MyClass myClass, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { myClass }; + System.Int32 returnData = (System.Int32)Client.Invoke(typeof(System.Int32), "POST:/apiserver/testpost?", invokeOption, parameters); + return returnData; + } -} -public class MyClass -{ -public System.Int32 A { get; set; } -public System.Int32 B { get; set; } -} + /// + ///无注释信息 + /// + public async Task TestPostAsync(MyClass myClass, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { myClass }; + return (System.Int32)await Client.InvokeAsync(typeof(System.Int32), "POST:/apiserver/testpost?", invokeOption, parameters); + } -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public System.String DownloadFile(System.String id, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { id }; + System.String returnData = (System.String)Client.Invoke(typeof(System.String), "GET:/apiserver/downloadfile?id={0}", invokeOption, parameters); + return returnData; + } + + /// + ///无注释信息 + /// + public async Task DownloadFileAsync(System.String id, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { id }; + return (System.String)await Client.InvokeAsync(typeof(System.String), "GET:/apiserver/downloadfile?id={0}", invokeOption, parameters); + } + + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public System.String PostContent(IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + System.String returnData = (System.String)Client.Invoke(typeof(System.String), "POST:/apiserver/postcontent", invokeOption, null); + return returnData; + } + + /// + ///无注释信息 + /// + public async Task PostContentAsync(IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + return (System.String)await Client.InvokeAsync(typeof(System.String), "POST:/apiserver/postcontent", invokeOption, null); + } + + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public System.String UploadMultiFile(System.String id, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { id }; + System.String returnData = (System.String)Client.Invoke(typeof(System.String), "POST:/apiserver/uploadmultifile?id={0}", invokeOption, parameters); + return returnData; + } + + /// + ///无注释信息 + /// + public async Task UploadMultiFileAsync(System.String id, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { id }; + return (System.String)await Client.InvokeAsync(typeof(System.String), "POST:/apiserver/uploadmultifile?id={0}", invokeOption, parameters); + } + + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public System.String UploadBigFile(IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + System.String returnData = (System.String)Client.Invoke(typeof(System.String), "POST:/apiserver/uploadbigfile", invokeOption, null); + return returnData; + } + + /// + ///无注释信息 + /// + public async Task UploadBigFileAsync(IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + return (System.String)await Client.InvokeAsync(typeof(System.String), "POST:/apiserver/uploadbigfile", invokeOption, null); + } + } + + public static class ApiServerExtensions + { + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static System.Int32 Sum(this TClient client, System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default) where TClient : + TouchSocket.WebApi.IWebApiClientBase + { + object[] parameters = new object[] { a, b }; + System.Int32 returnData = (System.Int32)client.Invoke(typeof(System.Int32), "GET:/apiserver/sumab?a={0}&b={1}", invokeOption, parameters); + return returnData; + } + + /// + ///无注释信息 + /// + public static async Task SumAsync(this TClient client, System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default) where TClient : + TouchSocket.WebApi.IWebApiClientBase + { + object[] parameters = new object[] { a, b }; + return (System.Int32)await client.InvokeAsync(typeof(System.Int32), "GET:/apiserver/sumab?a={0}&b={1}", invokeOption, parameters); + } + + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static MyClass GetMyClass(this TClient client, IInvokeOption invokeOption = default) where TClient : + TouchSocket.WebApi.IWebApiClientBase + { + MyClass returnData = (MyClass)client.Invoke(typeof(MyClass), "GET:/apiserver/getmyclass", invokeOption, null); + return returnData; + } + + /// + ///无注释信息 + /// + public static async Task GetMyClassAsync(this TClient client, IInvokeOption invokeOption = default) where TClient : + TouchSocket.WebApi.IWebApiClientBase + { + return (MyClass)await client.InvokeAsync(typeof(MyClass), "GET:/apiserver/getmyclass", invokeOption, null); + } + + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static System.Int32 TestPost(this TClient client, MyClass myClass, IInvokeOption invokeOption = default) where TClient : + TouchSocket.WebApi.IWebApiClientBase + { + object[] parameters = new object[] { myClass }; + System.Int32 returnData = (System.Int32)client.Invoke(typeof(System.Int32), "POST:/apiserver/testpost?", invokeOption, parameters); + return returnData; + } + + /// + ///无注释信息 + /// + public static async Task TestPostAsync(this TClient client, MyClass myClass, IInvokeOption invokeOption = default) where TClient : + TouchSocket.WebApi.IWebApiClientBase + { + object[] parameters = new object[] { myClass }; + return (System.Int32)await client.InvokeAsync(typeof(System.Int32), "POST:/apiserver/testpost?", invokeOption, parameters); + } + + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static System.String DownloadFile(this TClient client, System.String id, IInvokeOption invokeOption = default) where TClient : + TouchSocket.WebApi.IWebApiClientBase + { + object[] parameters = new object[] { id }; + System.String returnData = (System.String)client.Invoke(typeof(System.String), "GET:/apiserver/downloadfile?id={0}", invokeOption, parameters); + return returnData; + } + + /// + ///无注释信息 + /// + public static async Task DownloadFileAsync(this TClient client, System.String id, IInvokeOption invokeOption = default) where TClient : + TouchSocket.WebApi.IWebApiClientBase + { + object[] parameters = new object[] { id }; + return (System.String)await client.InvokeAsync(typeof(System.String), "GET:/apiserver/downloadfile?id={0}", invokeOption, parameters); + } + + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static System.String PostContent(this TClient client, IInvokeOption invokeOption = default) where TClient : + TouchSocket.WebApi.IWebApiClientBase + { + System.String returnData = (System.String)client.Invoke(typeof(System.String), "POST:/apiserver/postcontent", invokeOption, null); + return returnData; + } + + /// + ///无注释信息 + /// + public static async Task PostContentAsync(this TClient client, IInvokeOption invokeOption = default) where TClient : + TouchSocket.WebApi.IWebApiClientBase + { + return (System.String)await client.InvokeAsync(typeof(System.String), "POST:/apiserver/postcontent", invokeOption, null); + } + + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static System.String UploadMultiFile(this TClient client, System.String id, IInvokeOption invokeOption = default) where TClient : + TouchSocket.WebApi.IWebApiClientBase + { + object[] parameters = new object[] { id }; + System.String returnData = (System.String)client.Invoke(typeof(System.String), "POST:/apiserver/uploadmultifile?id={0}", invokeOption, parameters); + return returnData; + } + + /// + ///无注释信息 + /// + public static async Task UploadMultiFileAsync(this TClient client, System.String id, IInvokeOption invokeOption = default) where TClient : + TouchSocket.WebApi.IWebApiClientBase + { + object[] parameters = new object[] { id }; + return (System.String)await client.InvokeAsync(typeof(System.String), "POST:/apiserver/uploadmultifile?id={0}", invokeOption, parameters); + } + + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static System.String UploadBigFile(this TClient client, IInvokeOption invokeOption = default) where TClient : + TouchSocket.WebApi.IWebApiClientBase + { + System.String returnData = (System.String)client.Invoke(typeof(System.String), "POST:/apiserver/uploadbigfile", invokeOption, null); + return returnData; + } + + /// + ///无注释信息 + /// + public static async Task UploadBigFileAsync(this TClient client, IInvokeOption invokeOption = default) where TClient : + TouchSocket.WebApi.IWebApiClientBase + { + return (System.String)await client.InvokeAsync(typeof(System.String), "POST:/apiserver/uploadbigfile", invokeOption, null); + } + } + + public class MyClass + { + public System.Int32 A { get; set; } + public System.Int32 B { get; set; } + } +} \ No newline at end of file diff --git a/examples/WebSocket/AsyncWebSocketConsoleApp/Program.cs b/examples/WebSocket/AsyncWebSocketConsoleApp/Program.cs index 5e5900493..f21c01bf3 100644 --- a/examples/WebSocket/AsyncWebSocketConsoleApp/Program.cs +++ b/examples/WebSocket/AsyncWebSocketConsoleApp/Program.cs @@ -7,19 +7,14 @@ namespace SyncWebSocketConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var service = CreateHttpService(); using (var client = GetClient()) { - //通过GetWebSocket扩展方法,获取到显式的WebSocket终端。 - //需要注意的是,此处的using,仅仅是释放当前创建的WebSocket。而不是WebSocketClient的连接。 - using (var websocket=client.GetWebSocket()) + while (true) { - while (true) - { - websocket.Send(Console.ReadLine()); - } + client.Send(Console.ReadLine()); } } } @@ -67,7 +62,7 @@ namespace SyncWebSocketConsoleApp } } - class MyReadWebSocketPlugin : PluginBase, IWebSocketHandshakedPlugin + internal class MyReadWebSocketPlugin : PluginBase, IWebSocketHandshakedPlugin { private readonly ILog m_logger; @@ -75,37 +70,36 @@ namespace SyncWebSocketConsoleApp { this.m_logger = logger; } - public async Task OnWebSocketHandshaked(IHttpClientBase client, HttpContextEventArgs e) - { - using (var websocket = client.GetWebSocket()) - { - //此处即表明websocket已连接 - while (true) - { - using (var receiveResult=await websocket.ReadAsync(CancellationToken.None)) - { - - if (receiveResult.DataFrame==null) - { - break; - } - //判断是否为最后数据 - //例如发送方发送了一个10Mb的数据,接收时可能会多次接收,所以需要此属性判断。 - if (receiveResult.DataFrame.FIN) + public async Task OnWebSocketHandshaked(IWebSocket client, HttpContextEventArgs e) + { + //当WebSocket想要使用ReadAsync时,需要设置此值为true + client.AllowAsyncRead = true; + + //此处即表明websocket已连接 + while (true) + { + using (var receiveResult = await client.ReadAsync(CancellationToken.None)) + { + if (receiveResult.DataFrame == null) + { + break; + } + + //判断是否为最后数据 + //例如发送方发送了一个10Mb的数据,接收时可能会多次接收,所以需要此属性判断。 + if (receiveResult.DataFrame.FIN) + { + if (receiveResult.DataFrame.IsText) { - if (receiveResult.DataFrame.IsText) - { - m_logger.Info($"WebSocket文本:{receiveResult.DataFrame.ToText()}"); - } + this.m_logger.Info($"WebSocket文本:{receiveResult.DataFrame.ToText()}"); } - } } - - //此处即表明websocket已断开连接 - m_logger.Info("WebSocket断开连接"); } + + //此处即表明websocket已断开连接 + this.m_logger.Info("WebSocket断开连接"); await e.InvokeNext(); } } diff --git a/examples/WebSocket/WebSocketConsoleApp/Program.cs b/examples/WebSocket/WebSocketConsoleApp/Program.cs index 07391c559..51caa5740 100644 --- a/examples/WebSocket/WebSocketConsoleApp/Program.cs +++ b/examples/WebSocket/WebSocketConsoleApp/Program.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; -using System.Net.WebSockets; using System.Text; -using System.Threading; using System.Threading.Tasks; using TouchSocket.Core; using TouchSocket.Http; @@ -33,7 +31,6 @@ namespace WebSocketConsoleApp var service = CreateHttpService(); consoleAction.RunCommandLine(); - } private static async void SendAdd() @@ -55,10 +52,10 @@ namespace WebSocketConsoleApp .SetRemoteIPHost("ws://127.0.0.1:7789/ws")); client.Connect(); - client.SendWithWS("Add 10 20"); + client.Send("Add 10 20"); await Task.Delay(1000); - } + private static void SendSubstringText() { var client = new WebSocketClient(); @@ -70,10 +67,10 @@ namespace WebSocketConsoleApp .SetRemoteIPHost("ws://127.0.0.1:7789/ws")); client.Connect(); - for (int i = 0; i < 10; i++) + for (var i = 0; i < 10; i++) { var msg = Encoding.UTF8.GetBytes("hello"); - client.SendWithWS("Hello", i == 9); + client.Send("Hello", i == 9); } } @@ -87,7 +84,7 @@ namespace WebSocketConsoleApp }) .SetRemoteIPHost("ws://127.0.0.1:7789/ws")); client.Connect(); - client.SendWithWS("hello"); + client.Send("hello"); } private static void ConsoleAction_OnException(Exception obj) @@ -295,31 +292,37 @@ namespace WebSocketConsoleApp return false; } - public class MyWebSocketPlugin : PluginBase, IWebSocketHandshakingPlugin, IWebSocketHandshakedPlugin, IWebSocketReceivedPlugin { - public async Task OnWebSocketHandshaking(IHttpClientBase client, HttpContextEventArgs e) + public MyWebSocketPlugin(ILog logger) { - client.Logger.Info("WebSocket正在连接"); + this.m_logger = logger; + } + + public async Task OnWebSocketHandshaking(IWebSocket client, HttpContextEventArgs e) + { + this.m_logger.Info("WebSocket正在连接"); await e.InvokeNext(); } - public async Task OnWebSocketHandshaked(IHttpClientBase client, HttpContextEventArgs e) + public async Task OnWebSocketHandshaked(IWebSocket client, HttpContextEventArgs e) { - client.Logger.Info("WebSocket成功连接"); + this.m_logger.Info("WebSocket成功连接"); await e.InvokeNext(); } //此处使用字典,原因是插件是多客户端并发的,所以需要字典找到对应客户端的缓存 - Dictionary m_stringBuilders = new Dictionary();//接收临时Text + private Dictionary m_stringBuilders = new Dictionary();//接收临时Text - public async Task OnWebSocketReceived(IHttpClientBase client, WSDataFrameEventArgs e) + private readonly ILog m_logger; + + public async Task OnWebSocketReceived(IWebSocket client, WSDataFrameEventArgs e) { switch (e.DataFrame.Opcode) { case WSDataType.Cont: { - client.Logger.Info($"收到后续包长度:{e.DataFrame.PayloadLength}"); + this.m_logger.Info($"收到后续包长度:{e.DataFrame.PayloadLength}"); //找到客户端对应的缓存 if (this.m_stringBuilders.TryGetValue(client, out var stringBuilder))//后续包是文本 @@ -328,7 +331,7 @@ namespace WebSocketConsoleApp if (e.DataFrame.FIN)//完成接收后续包 { - client.Logger.Info($"完成接收后续包:{stringBuilder.ToString()}"); + this.m_logger.Info($"完成接收后续包:{stringBuilder.ToString()}"); this.m_stringBuilders.Remove(client);//置空 } } @@ -339,17 +342,16 @@ namespace WebSocketConsoleApp case WSDataType.Text: if (e.DataFrame.FIN)//一个包直接结束接收 { - client.Logger.Info(e.DataFrame.ToText()); + this.m_logger.Info(e.DataFrame.ToText()); - if (!client.IsClient) + if (!client.Client.IsClient) { - client.SendWithWS("我已收到"); + client.Send("我已收到"); } } else//一个包没有结束,还有后续包 { - client.Logger.Info($"收到未完成的文本:{e.DataFrame.PayloadLength}"); - + this.m_logger.Info($"收到未完成的文本:{e.DataFrame.PayloadLength}"); var stringBuilder = new StringBuilder(); stringBuilder.Append(e.DataFrame.ToText()); @@ -364,27 +366,27 @@ namespace WebSocketConsoleApp //可以拿到二进制数据。实际上也不需要ToArray。直接使用PayloadData可能更高效。 //具体资料可以参考内存池 var bytes = e.DataFrame.PayloadData.ToArray(); - client.Logger.Info($"收到二进制数据,长度为:{e.DataFrame.PayloadLength}"); + this.m_logger.Info($"收到二进制数据,长度为:{e.DataFrame.PayloadLength}"); } else { - client.Logger.Info($"收到未结束的二进制数据,长度为:{e.DataFrame.PayloadLength}"); + this.m_logger.Info($"收到未结束的二进制数据,长度为:{e.DataFrame.PayloadLength}"); } return; case WSDataType.Close: { - client.Logger.Info("远程请求断开"); + this.m_logger.Info("远程请求断开"); client.Close("断开"); } return; case WSDataType.Ping: - client.Logger.Info("Ping"); + this.m_logger.Info("Ping"); break; case WSDataType.Pong: - client.Logger.Info("Pong"); + this.m_logger.Info("Pong"); break; default: @@ -395,7 +397,7 @@ namespace WebSocketConsoleApp } } - class MyHttpPlugin : PluginBase, IHttpPlugin + private class MyHttpPlugin : PluginBase, IHttpPlugin { public async Task OnHttpRequest(IHttpSocketClient client, HttpContextEventArgs e) { diff --git a/examples/XmlRpc/DispatchProxyXmlRpcClientConsoleApp/Program.cs b/examples/XmlRpc/DispatchProxyXmlRpcClientConsoleApp/Program.cs index f5927f51d..e8658e07e 100644 --- a/examples/XmlRpc/DispatchProxyXmlRpcClientConsoleApp/Program.cs +++ b/examples/XmlRpc/DispatchProxyXmlRpcClientConsoleApp/Program.cs @@ -1,21 +1,20 @@ -using TouchSocket.Core; -using TouchSocket.Sockets; +using TouchSocket.Sockets; using TouchSocket.XmlRpc; namespace DispatchProxyXmlRpcClientConsoleApp { internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var rpc = MyXmlRpcDispatchProxy.Create(); while (true) { Console.WriteLine("请输入两个数,中间用空格隔开,回车确认"); - string str = Console.ReadLine(); + var str = Console.ReadLine(); var strs = str.Split(' '); - int a = int.Parse(strs[0]); - int b = int.Parse(strs[1]); + var a = int.Parse(strs[0]); + var b = int.Parse(strs[1]); var sum = rpc.Sum(a, b); Console.WriteLine(sum); @@ -27,7 +26,7 @@ namespace DispatchProxyXmlRpcClientConsoleApp /// 新建一个类,继承XmlRpcDispatchProxy,亦或者RpcDispatchProxy基类。 /// 然后实现抽象方法,主要是能获取到调用的IRpcClient派生接口。 /// - class MyXmlRpcDispatchProxy : XmlRpcDispatchProxy + internal class MyXmlRpcDispatchProxy : XmlRpcDispatchProxy { private readonly IXmlRpcClient m_client; @@ -35,6 +34,7 @@ namespace DispatchProxyXmlRpcClientConsoleApp { this.m_client = GetXmlRpcClient(); } + public override IXmlRpcClient GetClient() { return this.m_client; @@ -49,7 +49,7 @@ namespace DispatchProxyXmlRpcClientConsoleApp } } - interface IXmlRpcServer + internal interface IXmlRpcServer { [XmlRpc(true)] int Sum(int a, int b); diff --git a/examples/XmlRpc/XmlRpcServerApp/Program.cs b/examples/XmlRpc/XmlRpcServerApp/Program.cs index f786441a8..2ce1abe91 100644 --- a/examples/XmlRpc/XmlRpcServerApp/Program.cs +++ b/examples/XmlRpc/XmlRpcServerApp/Program.cs @@ -40,9 +40,8 @@ namespace XmlRpcServerApp Console.ReadKey(); } - static void a() + private static void a() { - } } diff --git a/examples/XmlRpc/XmlRpcServerApp/RpcProxy.cs b/examples/XmlRpc/XmlRpcServerApp/RpcProxy.cs index 5af137069..bada7f6f2 100644 --- a/examples/XmlRpc/XmlRpcServerApp/RpcProxy.cs +++ b/examples/XmlRpc/XmlRpcServerApp/RpcProxy.cs @@ -2,165 +2,177 @@ 此代码由Rpc工具直接生成,非必要请不要修改此处代码 */ #pragma warning disable + using System; -using TouchSocket.Core; -using TouchSocket.Sockets; -using TouchSocket.Rpc; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading.Tasks; +using TouchSocket.Core; +using TouchSocket.Rpc; +using TouchSocket.Sockets; + namespace RpcProxy { -public interface IXmlServer:TouchSocket.Rpc.IRemoteServer -{ -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -System.Int32 Sum(System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task SumAsync(System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default); + public interface IXmlServer : TouchSocket.Rpc.IRemoteServer + { + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + System.Int32 Sum(System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -System.Int32 TestClass(MyClass myClass,IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -Task TestClassAsync(MyClass myClass,IInvokeOption invokeOption = default); + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task SumAsync(System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default); -} -public class XmlServer :IXmlServer -{ -public XmlServer(IRpcClient client) -{ -this.Client=client; -} -public IRpcClient Client{get;private set; } -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public System.Int32 Sum(System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{a,b}; -System.Int32 returnData=(System.Int32)Client.Invoke(typeof(System.Int32),"Sum",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public async Task SumAsync(System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{a,b}; -return (System.Int32) await Client.InvokeAsync(typeof(System.Int32),"Sum",invokeOption, parameters); -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + System.Int32 TestClass(MyClass myClass, IInvokeOption invokeOption = default); -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public System.Int32 TestClass(MyClass myClass,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{myClass}; -System.Int32 returnData=(System.Int32)Client.Invoke(typeof(System.Int32),"TestClass",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public async Task TestClassAsync(MyClass myClass,IInvokeOption invokeOption = default) -{ -if(Client==null) -{ -throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); -} -object[] parameters = new object[]{myClass}; -return (System.Int32) await Client.InvokeAsync(typeof(System.Int32),"TestClass",invokeOption, parameters); -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + Task TestClassAsync(MyClass myClass, IInvokeOption invokeOption = default); + } -} -public static class XmlServerExtensions -{ -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static System.Int32 Sum(this TClient client,System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default) where TClient: -TouchSocket.XmlRpc.IXmlRpcClient{ -object[] parameters = new object[]{a,b}; -System.Int32 returnData=(System.Int32)client.Invoke(typeof(System.Int32),"Sum",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public static async Task SumAsync(this TClient client,System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default) where TClient: -TouchSocket.XmlRpc.IXmlRpcClient{ -object[] parameters = new object[]{a,b}; -return (System.Int32) await client.InvokeAsync(typeof(System.Int32),"Sum",invokeOption, parameters); -} + public class XmlServer : IXmlServer + { + public XmlServer(IRpcClient client) + { + this.Client = client; + } -/// -///无注释信息 -/// -/// 调用超时 -/// Rpc调用异常 -/// 其他异常 -public static System.Int32 TestClass(this TClient client,MyClass myClass,IInvokeOption invokeOption = default) where TClient: -TouchSocket.XmlRpc.IXmlRpcClient{ -object[] parameters = new object[]{myClass}; -System.Int32 returnData=(System.Int32)client.Invoke(typeof(System.Int32),"TestClass",invokeOption, parameters); -return returnData; -} -/// -///无注释信息 -/// -public static async Task TestClassAsync(this TClient client,MyClass myClass,IInvokeOption invokeOption = default) where TClient: -TouchSocket.XmlRpc.IXmlRpcClient{ -object[] parameters = new object[]{myClass}; -return (System.Int32) await client.InvokeAsync(typeof(System.Int32),"TestClass",invokeOption, parameters); -} + public IRpcClient Client { get; private set; } -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public System.Int32 Sum(System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { a, b }; + System.Int32 returnData = (System.Int32)Client.Invoke(typeof(System.Int32), "Sum", invokeOption, parameters); + return returnData; + } -public class MyClass -{ -public System.Int32 A{get;set;} -public System.Int32 B{get;set;} -} + /// + ///无注释信息 + /// + public async Task SumAsync(System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { a, b }; + return (System.Int32)await Client.InvokeAsync(typeof(System.Int32), "Sum", invokeOption, parameters); + } -} + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public System.Int32 TestClass(MyClass myClass, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { myClass }; + System.Int32 returnData = (System.Int32)Client.Invoke(typeof(System.Int32), "TestClass", invokeOption, parameters); + return returnData; + } + + /// + ///无注释信息 + /// + public async Task TestClassAsync(MyClass myClass, IInvokeOption invokeOption = default) + { + if (Client == null) + { + throw new RpcException("IRpcClient为空,请先初始化或者进行赋值"); + } + object[] parameters = new object[] { myClass }; + return (System.Int32)await Client.InvokeAsync(typeof(System.Int32), "TestClass", invokeOption, parameters); + } + } + + public static class XmlServerExtensions + { + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static System.Int32 Sum(this TClient client, System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default) where TClient : + TouchSocket.XmlRpc.IXmlRpcClient + { + object[] parameters = new object[] { a, b }; + System.Int32 returnData = (System.Int32)client.Invoke(typeof(System.Int32), "Sum", invokeOption, parameters); + return returnData; + } + + /// + ///无注释信息 + /// + public static async Task SumAsync(this TClient client, System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default) where TClient : + TouchSocket.XmlRpc.IXmlRpcClient + { + object[] parameters = new object[] { a, b }; + return (System.Int32)await client.InvokeAsync(typeof(System.Int32), "Sum", invokeOption, parameters); + } + + /// + ///无注释信息 + /// + /// 调用超时 + /// Rpc调用异常 + /// 其他异常 + public static System.Int32 TestClass(this TClient client, MyClass myClass, IInvokeOption invokeOption = default) where TClient : + TouchSocket.XmlRpc.IXmlRpcClient + { + object[] parameters = new object[] { myClass }; + System.Int32 returnData = (System.Int32)client.Invoke(typeof(System.Int32), "TestClass", invokeOption, parameters); + return returnData; + } + + /// + ///无注释信息 + /// + public static async Task TestClassAsync(this TClient client, MyClass myClass, IInvokeOption invokeOption = default) where TClient : + TouchSocket.XmlRpc.IXmlRpcClient + { + object[] parameters = new object[] { myClass }; + return (System.Int32)await client.InvokeAsync(typeof(System.Int32), "TestClass", invokeOption, parameters); + } + } + + public class MyClass + { + public System.Int32 A { get; set; } + public System.Int32 B { get; set; } + } +} \ No newline at end of file diff --git a/handbook/docs/websocketclient.mdx b/handbook/docs/websocketclient.mdx index c4d34e9d6..b7506e73d 100644 --- a/handbook/docs/websocketclient.mdx +++ b/handbook/docs/websocketclient.mdx @@ -126,7 +126,7 @@ client.Setup(new TouchSocketConfig() }) .ConfigurePlugins(a => { - a.Add(nameof(IWebSocketHandshakingPlugin.OnWebSocketHandshaking), async (IHttpClientBase client, HttpContextEventArgs e) => + a.Add(nameof(IWebSocketHandshakingPlugin.OnWebSocketHandshaking), async (IWebSocket client, HttpContextEventArgs e) => { e.Context.Request.Headers.Add("token", "123456"); await e.InvokeNext(); @@ -157,7 +157,7 @@ client.Setup(new TouchSocketConfig() }) .ConfigurePlugins(a => { - a.Add(nameof(IWebSocketHandshakingPlugin.OnWebSocketHandshaking), async (IHttpClientBase client, HttpContextEventArgs e) => + a.Add(nameof(IWebSocketHandshakingPlugin.OnWebSocketHandshaking), async (IWebSocket client, HttpContextEventArgs e) => { e.Context.Request.Method = HttpMethod.Post;//将请求方法改为Post await e.InvokeNext(); @@ -183,13 +183,13 @@ client.Logger.Info("通过ws://127.0.0.1:7789/postws连接成功"); ### 5.1 发送文本类消息 ```csharp showLineNumbers -client.SendWithWS("Text"); +client.Send("Text"); ``` ### 5.2 发送二进制消息 ```csharp showLineNumbers -client.SendWithWS(new byte[10]); +client.Send(new byte[10]); ``` ### 5.3 直接发送自定义构建的数据帧 @@ -203,7 +203,8 @@ frame.RSV3= true; frame.AppendText("I"); frame.AppendText("Love"); frame.AppendText("U"); -myWSClient.SendWithWS(frame); + +client.Send(frame); ``` :::info 备注 @@ -211,12 +212,6 @@ myWSClient.SendWithWS(frame); ::: -:::caution 注意 - -Websocket的所有发送,都是形如**SendWithWS**的扩展方法。不可直接Send。 - -::: - ## 六、接收数据 ### 6.1 订阅Received事件实现 @@ -248,40 +243,46 @@ client.Received = (c, e) => 【定义插件】 ```csharp showLineNumbers -public class MyWebSocketPlugin : PluginBase,IWebSocketReceivedPlugin +public class MyWebSocketPlugin : PluginBase, IWebSocketReceivedPlugin { - public async Task OnWebSocketReceived(IHttpClientBase client, WSDataFrameEventArgs e) + private readonly ILog m_logger; + + public MyWebSocketPlugin(ILog logger) + { + this.m_logger = logger; + } + public async Task OnWebSocketReceived(IWebSocket client, WSDataFrameEventArgs e) { switch (e.DataFrame.Opcode) { case WSDataType.Cont: - client.Logger.Info($"收到中间数据,长度为:{e.DataFrame.PayloadLength}"); + m_logger.Info($"收到中间数据,长度为:{e.DataFrame.PayloadLength}"); return; case WSDataType.Text: - client.Logger.Info(e.DataFrame.ToText()); + m_logger.Info(e.DataFrame.ToText()); - if (!client.IsClient) + if (!client.Client.IsClient) { - client.SendWithWS("我已收到"); + client.Send("我已收到"); } return; case WSDataType.Binary: if (e.DataFrame.FIN) { - client.Logger.Info($"收到二进制数据,长度为:{e.DataFrame.PayloadLength}"); + m_logger.Info($"收到二进制数据,长度为:{e.DataFrame.PayloadLength}"); } else { - client.Logger.Info($"收到未结束的二进制数据,长度为:{e.DataFrame.PayloadLength}"); + m_logger.Info($"收到未结束的二进制数据,长度为:{e.DataFrame.PayloadLength}"); } return; case WSDataType.Close: { - client.Logger.Info("远程请求断开"); + m_logger.Info("远程请求断开"); client.Close("断开"); } return; @@ -323,28 +324,26 @@ client.Connect(); ```csharp showLineNumbers using (var client = GetClient()) { - //通过GetWebSocket扩展方法,获取到显式的WebSocket终端。 - //需要注意的是,此处的using,仅仅是释放当前创建的WebSocket。而不是WebSocketClient的连接。 - using (var websocket=client.GetWebSocket()) - { - while (true) - { - using (var receiveResult = await websocket.ReadAsync(CancellationToken.None)) - { - if (receiveResult.DataFrame == null) - { - //断开连接了 - break; - } + //当WebSocket想要使用ReadAsync时,需要设置此值为true + client.AllowAsyncRead = true; - //判断是否为最后数据 - //例如发送方发送了一个10Mb的数据,接收时可能会多次接收,所以需要此属性判断。 - if (receiveResult.DataFrame.FIN) + while (true) + { + using (var receiveResult = await client.ReadAsync(CancellationToken.None)) + { + if (receiveResult.IsClosed) + { + //断开连接了 + break; + } + + //判断是否为最后数据 + //例如发送方发送了一个10Mb的数据,接收时可能会多次接收,所以需要此属性判断。 + if (receiveResult.DataFrame.FIN) + { + if (receiveResult.DataFrame.IsText) { - if (receiveResult.DataFrame.IsText) - { - m_logger.Info($"WebSocket文本:{receiveResult.DataFrame.ToText()}"); - } + Console.WriteLine($"WebSocket文本:{receiveResult.DataFrame.ToText()}"); } } } @@ -360,7 +359,7 @@ using (var client = GetClient()) :::caution 注意 -使用该方式,会阻塞`IWebSocketHandshakedPlugin`的插件传递。并且被调用`GetWebSocket`的客户端,在收到`WebSocket`消息的时候,不会再触发插件。 +使用该方式,会阻塞`IWebSocketHandshakedPlugin`的插件传递。在收到`WebSocket`消息的时候,不会再触发插件。 ::: @@ -368,20 +367,20 @@ using (var client = GetClient()) ### 7.1 握手机制 -`WebSocket`是从HttpClient、TcpClient继承来的,所以很多属性仅仅是表示Tcp的状态。要获取握手信息,需要调用client.GetHandshaked()扩展方法获得。 +`WebSocket`拥有独立的握手机制,直接获取`IsHandshaked`属性即可。 ### 7.2 Ping机制 -`WebSocket`有自己的Ping、Pong机制。所以直接调用已有方法即可。 +`WebSocket`有自己的`Ping`、`Pong`机制。所以直接调用已有方法即可。 ```csharp showLineNumbers -client.PingWS(); -client.PongWS(); +client.Ping(); +client.Pong(); ``` :::tip 建议 -WebSocket是双向通讯,所以支持客户端和服务器双向操作Ping和Pong报文。但是一般来说都是客户端执行Ping,服务器回应Pong。 +`WebSocket`是双向通讯,所以支持客户端和服务器双向操作`Ping`和`Pong`报文。但是一般来说都是客户端执行`Ping`,服务器回应`Pong`。 ::: @@ -401,7 +400,7 @@ WebSocket是双向通讯,所以支持客户端和服务器双向操作Ping和P 关闭Websocket,应该发送关闭报文。 ```csharp showLineNumbers -myWSClient.CloseWithWS("close"); +myWSClient.Close("close"); ``` [本文示例Demo](https://gitee.com/RRQM_Home/TouchSocket/tree/master/examples/WebSocket/WebSocketConsoleApp) diff --git a/handbook/docs/websocketservice.mdx b/handbook/docs/websocketservice.mdx index c1dc6c242..94233b9b0 100644 --- a/handbook/docs/websocketservice.mdx +++ b/handbook/docs/websocketservice.mdx @@ -10,7 +10,7 @@ title: 创建WebSocket服务器 ## 一、说明 -WebSocket是基于Http协议的升级协议,所以应当挂载在http服务器执行。 +`WebSocket`是基于`Http`协议的升级协议,所以应当挂载在`http`服务器执行。 ## 二、可配置项 @@ -31,7 +31,7 @@ WebSocket是基于Http协议的升级协议,所以应当挂载在http服务器 ### 4.1 简单直接创建 -通过插件创建的话,只能指定一个特殊url路由。如果想获得连接前的Http请求,也必须再添加一个实现IWebSocketPlugin接口的插件,然后从OnHandshaking方法中捕获。 +通过插件创建的话,只能指定一个特殊`url`路由。如果想获得连接前的`Http`请求,也必须再添加一个实现`IWebSocketPlugin`接口的插件,然后从`OnHandshaking`方法中捕获。 ```csharp showLineNumbers var service = new HttpService(); @@ -55,7 +55,7 @@ service.Logger.Info("服务器已启动"); ### 4.2 验证连接 -可以对连接的Url、Query、Header等参数进行验证,然后决定是否执行WebSocket连接。 +可以对连接的`Url`、`Query`、`Header`等参数进行验证,然后决定是否执行`WebSocket`连接。 ```csharp showLineNumbers var service = new HttpService(); @@ -129,8 +129,8 @@ private static bool VerifyConnection(IHttpSocketClient client, HttpContext conte 通过WebApi的方式会更加灵活,也能很方便的获得Http相关参数。还能实现多个Url的连接路由。 实现步骤: -1. 必须配置ConfigureRpcStore,和注册MyServer -2. 必须添加WebApiParserPlugin +1. 必须配置`ConfigureRpcStore`,和注册`MyServer` +2. 必须添加`WebApiParserPlugin` ```csharp showLineNumbers var service = new HttpService(); @@ -181,16 +181,16 @@ public class MyServer : RpcServer ### 4.4 通过Http上下文直接创建 -使用上下文直接创建的优点在于能更加个性化的实现WebSocket的连接。 +使用上下文直接创建的优点在于能更加个性化的实现`WebSocket`的连接。 ```csharp showLineNumbers -class MyHttpPlugin : PluginBase, IHttpGetPlugin +class MyHttpPlugin : PluginBase, IHttpPlugin { - public async Task OnHttpGet(IHttpSocketClient client, HttpContextEventArgs e) + public async Task OnHttpRequest(IHttpSocketClient client, HttpContextEventArgs e) { if (e.Context.Request.UrlEquals("/GetSwitchToWebSocket")) { - bool result = client.SwitchProtocolToWebSocket(e.Context); + var result =await client.SwitchProtocolToWebSocket(e.Context); return; } await e.InvokeNext(); @@ -200,7 +200,7 @@ class MyHttpPlugin : PluginBase, IHttpGetPlugin ### 4.5 创建基于Ssl的WebSocket服务 -创建WSs服务器时,其他配置不变,只需要在config中配置SslOption代码即可,放置了一个自制Ssl证书,密码为“RRQMSocket”以供测试。使用配置非常方便。 +创建`WSs`服务器时,其他配置不变,只需要在`config`中配置`SslOption`代码即可,放置了一个自制`Ssl`证书,密码为“RRQMSocket”以供测试。使用配置非常方便。 ```csharp showLineNumbers var config = new TouchSocketConfig(); @@ -214,7 +214,7 @@ config.SetServiceSslOption(new ServiceSslOption() //Ssl配置,当为null的时 ## 五、接收消息 -WebSocket服务器接收消息,目前有两种方式。第一种就是通过订阅`IWebSocketReceivedPlugin`插件完全异步的接收消息。第二种就是调用`GetWebSocket`扩展方法。获取到显式的WebSocket对象,然后调用`ReadAsync`方法异步阻塞式读取。 +WebSocket服务器接收消息,目前有两种方式。第一种就是通过订阅`IWebSocketReceivedPlugin`插件完全异步的接收消息。第二种就是调用`WebSocket`,然后调用`ReadAsync`方法异步阻塞式读取。 ### 5.1 插件接收消息 @@ -223,38 +223,44 @@ WebSocket服务器接收消息,目前有两种方式。第一种就是通过 ```csharp showLineNumbers public class MyWebSocketPlugin : PluginBase, IWebSocketReceivedPlugin { - public async Task OnWebSocketReceived(IHttpClientBase client, WSDataFrameEventArgs e) + private readonly ILog m_logger; + + public MyWebSocketPlugin(ILog logger) + { + this.m_logger = logger; + } + public async Task OnWebSocketReceived(IWebSocket client, WSDataFrameEventArgs e) { switch (e.DataFrame.Opcode) { case WSDataType.Cont: - client.Logger.Info($"收到中间数据,长度为:{e.DataFrame.PayloadLength}"); + m_logger.Info($"收到中间数据,长度为:{e.DataFrame.PayloadLength}"); return; case WSDataType.Text: - client.Logger.Info(e.DataFrame.ToText()); + m_logger.Info(e.DataFrame.ToText()); - if (!client.IsClient) + if (!client.Client.IsClient) { - client.SendWithWS("我已收到"); + client.Send("我已收到"); } return; case WSDataType.Binary: if (e.DataFrame.FIN) { - client.Logger.Info($"收到二进制数据,长度为:{e.DataFrame.PayloadLength}"); + m_logger.Info($"收到二进制数据,长度为:{e.DataFrame.PayloadLength}"); } else { - client.Logger.Info($"收到未结束的二进制数据,长度为:{e.DataFrame.PayloadLength}"); + m_logger.Info($"收到未结束的二进制数据,长度为:{e.DataFrame.PayloadLength}"); } return; case WSDataType.Close: { - client.Logger.Info("远程请求断开"); + m_logger.Info("远程请求断开"); client.Close("断开"); } return; @@ -313,34 +319,37 @@ class MyReadWebSocketPlugin : PluginBase, IWebSocketHandshakedPlugin { this.m_logger = logger; } - public async Task OnWebSocketHandshaked(IHttpClientBase client, HttpContextEventArgs e) + public async Task OnWebSocketHandshaked(IWebSocket client, HttpContextEventArgs e) { - using (var websocket = client.GetWebSocket()) + //当WebSocket想要使用ReadAsync时,需要设置此值为true + client.AllowAsyncRead = true; + + //此处即表明websocket已连接 + while (true) { - //此处即表明websocket已连接 - while (true) + using (var receiveResult = await client.ReadAsync(CancellationToken.None)) { - using (var receiveResult=await websocket.ReadAsync(CancellationToken.None)) + + if (receiveResult.DataFrame == null) { - if (receiveResult.DataFrame==null) + break; + } + + //判断是否为最后数据 + //例如发送方发送了一个10Mb的数据,接收时可能会多次接收,所以需要此属性判断。 + if (receiveResult.DataFrame.FIN) + { + if (receiveResult.DataFrame.IsText) { - break; - } - //判断是否为最后数据 - //例如发送方发送了一个10Mb的数据,接收时可能会多次接收,所以需要此属性判断。 - if (receiveResult.DataFrame.FIN) - { - if (receiveResult.DataFrame.IsText) - { - m_logger.Info($"WebSocket文本:{receiveResult.DataFrame.ToText()}"); - } + m_logger.Info($"WebSocket文本:{receiveResult.DataFrame.ToText()}"); } } - } - //此处即表明websocket已断开连接 - m_logger.Info("WebSocket断开连接"); + } } + + //此处即表明websocket已断开连接 + m_logger.Info("WebSocket断开连接"); await e.InvokeNext(); } } @@ -383,13 +392,13 @@ private static HttpService CreateHttpService() :::caution 注意 -使用该方式,会阻塞`IWebSocketHandshakedPlugin`的插件传递。并且被调用`GetWebSocket`的客户端,在收到`WebSocket`消息的时候,不会再触发插件。 +使用该方式,会阻塞`IWebSocketHandshakedPlugin`的插件传递。在收到`WebSocket`消息的时候,不会再触发插件。 ::: ## 六、回复、响应数据 -要回复Websocket消息,必须使用**HttpSocketClient**对象。 +要回复`Websocket`消息,必须使用**HttpSocketClient**对象。 ### 6.1 如何获取SocketClient? @@ -413,13 +422,13 @@ foreach (var item in socketClients) :::caution 注意 -由于HttpSocketClient的生命周期是由框架控制的,所以最好尽量不要直接引用该实例,可以引用HttpSocketClient.Id,然后再通过服务器查找。 +由于`HttpSocketClient`的生命周期是由框架控制的,所以最好尽量不要直接引用该实例,可以引用`HttpSocketClient.Id`,然后再通过服务器查找。 ::: #### (2)通过Id获取 -先调用`service.GetIds`方法,获取当前在线的所有客户端的Id,然后选择需要的Id,通过TryGetSocketClient方法,获取到想要的客户端。 +先调用`service.GetIds`方法,获取当前在线的所有客户端的Id,然后选择需要的Id,通过`TryGetSocketClient`方法,获取到想要的客户端。 ```csharp showLineNumbers string[] ids = service.GetIds(); @@ -431,25 +440,17 @@ if (service.TryGetSocketClient(ids[0], out HttpSocketClient socketClient)) ### 6.2 发送文本类消息 ```csharp showLineNumbers -socketClient.SendWithWS("Text"); +socketClient.WebSocket.Send("Text"); ``` ### 6.3 发送二进制消息 ```csharp showLineNumbers -socketClient.SendWithWS(new byte[10]); +socketClient.WebSocket.Send(new byte[10]); ``` -### 6.4 发送分包的二进制 -例如:发送的数据为[0,1,2,3,4,5,6,7,8,9],当设置packageSize为5时,会先发送[0,1,2,3,4]作为头包,然后发送[5,6,7,8,9]的后继包。 - -```csharp showLineNumbers -byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; -socketClient.SubSendWithWS(data, 5); -``` - -### 6.5 直接发送自定义构建的数据帧 +### 6.4 直接发送自定义构建的数据帧 ```csharp showLineNumbers WSDataFrame frame=new WSDataFrame(); frame.Opcode= WSDataType.Text; @@ -460,18 +461,14 @@ frame.RSV3= true; frame.AppendText("I"); frame.AppendText("Love"); frame.AppendText("U"); -socketClient.SendWithWS(frame); + +socketClient.WebSocket.Send(frame); ``` + + :::info 备注 -此部分功能就需要你对Websocket有充分了解才可以操作。 - -::: - - -:::caution 注意 - -Websocket的所有发送,都是形如**SendWithWS**的扩展方法。不可直接Send。 +此部分功能就需要你对`WebSocket`有充分了解才可以操作。 ::: @@ -484,7 +481,7 @@ foreach (var item in service.GetClients()) { if (item.Protocol== Protocol.WebSocket) { - item.SendWithWS("广播"); + item.WebSocket.Send("广播"); } } ```