更新文档

This commit is contained in:
若汝棋茗
2024-03-03 19:18:05 +08:00
parent 6d50b26938
commit 890c2fce65
85 changed files with 2385 additions and 2370 deletions

View File

@@ -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

View File

@@ -1,5 +1,4 @@
using TouchSocket.Core;
using TouchSocket.Sockets;
namespace AdapterTesterConsoleApp
{

View File

@@ -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<MyRequestInfo>
{
/// <summary>
/// 筛选解析数据。实例化的TRequest会一直保存直至解析成功或手动清除。
/// <para>当不满足解析条件时,请返回<see cref="FilterResult.Cache"/>,此时会保存<see cref="ByteBlock.CanReadLen"/>的数据</para>
@@ -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];

View File

@@ -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
/// </summary>
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;
}
}
}

View File

@@ -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;
};

View File

@@ -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)

View File

@@ -137,21 +137,29 @@ namespace ServiceConsoleApp
/// <summary>
/// WS收到数据等业务。
/// </summary>
internal class MyWebSocketPlug : PluginBase, IWebSocketHandshakedPlugin<IHttpSocketClient>, IWebSocketReceivedPlugin<IHttpSocketClient>
internal class MyWebSocketPlug : PluginBase, IWebSocketHandshakedPlugin<IWebSocket>, IWebSocketReceivedPlugin<IWebSocket>
{
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();
}
}
}

View File

@@ -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]

View File

@@ -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; }
}

View File

@@ -14,10 +14,11 @@ namespace IocConsoleApp
PropertyInject();
MethodInject();
}
/// <summary>
/// 构造函数注入
/// </summary>
static void ConstructorInject()
private static void ConstructorInject()
{
var container = GetContainer();
container.RegisterSingleton<MyClass1>();
@@ -32,7 +33,7 @@ namespace IocConsoleApp
/// <summary>
/// 属性注入
/// </summary>
static void PropertyInject()
private static void PropertyInject()
{
var container = GetContainer();
container.RegisterSingleton<MyClass1>();
@@ -48,7 +49,7 @@ namespace IocConsoleApp
/// <summary>
/// 方法注入
/// </summary>
static void MethodInject()
private static void MethodInject()
{
var container = GetContainer();
container.RegisterSingleton<MyClass1>();
@@ -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
{
/// <summary>
/// 直接按类型,默认方式获取
@@ -103,11 +102,10 @@ namespace IocConsoleApp
public MyClass1 KeyMyClass1 { get; set; }
}
class MyClass4
internal class MyClass4
{
public MyClass1 MyClass1 { get; private set; }
[DependencyInject]
public void MethodInject(MyClass1 myClass1)
{

View File

@@ -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();
}
}
}

View File

@@ -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<IInterface10>();
var interface11 = container.Resolve<IInterface11>();
}
@@ -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
{
}
}

View File

@@ -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)

View File

@@ -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
/// </summary>
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");
}
}
}

View File

@@ -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);
}
}

View File

@@ -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:

View File

@@ -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)
{

View File

@@ -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
}
}
}
}

View File

@@ -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<SimpleDmtpRpcFeature>();
}
#endregion
/// <summary>
@@ -69,5 +65,4 @@ namespace CustomDmtpActorConsoleApp.SimpleDmtpRpc
smtpActor.SetValue(SimpleDmtpRpcActorProperty, smtpRpcActor);
}
}
}

View File

@@ -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<string, MethodModel> m_pairs = new Dictionary<string, MethodModel>();
private readonly Dictionary<string, MethodModel> m_pairs = new Dictionary<string, MethodModel>();
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();
}
}
}

View File

@@ -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项目
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
private static void Main(string[] args)
{
var myRpcServer = DmtpRpcDispatchProxy.Create<IMyRpcServer, MyDmtpRpcDispatchProxy>();
@@ -26,7 +24,7 @@ namespace DispatchProxyDmtpRpcConsoleApp
/// 新建一个类按照需要继承DmtpRpcDispatchProxy亦或者预设的JsonRpcDispatchProxy亦或者RpcDispatchProxy基类。
/// 然后实现抽象方法主要是能获取到调用的IRpcClient派生接口。
/// </summary>
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
{
/// <summary>
/// 将两个数相加

View File

@@ -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();

View File

@@ -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字节");
}
}
}

View File

@@ -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连接
/// </summary>
/// <returns></returns>
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。
/// </summary>
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}");
//向客户端回发消息

View File

@@ -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();

View File

@@ -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)

View File

@@ -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();
});

View File

@@ -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
{
///<summary>
///登录
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Boolean Login(System.String account,System.String password,IInvokeOption invokeOption = default);
///<summary>
///登录
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Boolean> LoginAsync(System.String account,System.String password,IInvokeOption invokeOption = default);
public interface IMyRpcServer : TouchSocket.Rpc.IRemoteServer
{
///<summary>
///登录
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Boolean Login(System.String account, System.String password, IInvokeOption invokeOption = default);
///<summary>
///注册
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Boolean Register(RegisterModel register,IInvokeOption invokeOption = default);
///<summary>
///注册
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Boolean> RegisterAsync(RegisterModel register,IInvokeOption invokeOption = default);
///<summary>
///登录
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Boolean> LoginAsync(System.String account, System.String password, IInvokeOption invokeOption = default);
///<summary>
///性能测试
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Int32 Performance(System.Int32 a,IInvokeOption invokeOption = default);
///<summary>
///性能测试
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Int32> PerformanceAsync(System.Int32 a,IInvokeOption invokeOption = default);
///<summary>
///注册
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Boolean Register(RegisterModel register, IInvokeOption invokeOption = default);
///<summary>
///测试out
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Boolean OutBytes(out System.Byte[] bytes,IInvokeOption invokeOption = default);
///<summary>
///测试out
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Boolean> OutBytesAsync(out System.Byte[] bytes,IInvokeOption invokeOption = default);
///<summary>
///注册
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Boolean> RegisterAsync(RegisterModel register, IInvokeOption invokeOption = default);
}
public class MyRpcServer :IMyRpcServer
{
public MyRpcServer(IRpcClient client)
{
this.Client=client;
}
public IRpcClient Client{get;private set; }
///<summary>
///登录
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///登录
///</summary>
public async Task<System.Boolean> 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);
}
///<summary>
///性能测试
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Int32 Performance(System.Int32 a, IInvokeOption invokeOption = default);
///<summary>
///注册
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///注册
///</summary>
public async Task<System.Boolean> 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);
}
///<summary>
///性能测试
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Int32> PerformanceAsync(System.Int32 a, IInvokeOption invokeOption = default);
///<summary>
///性能测试
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///性能测试
///</summary>
public async Task<System.Int32> 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);
}
///<summary>
///测试out
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Boolean OutBytes(out System.Byte[] bytes, IInvokeOption invokeOption = default);
///<summary>
///测试out
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///测试out
///</summary>
public Task<System.Boolean> 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<System.Boolean>(returnData);
}
///<summary>
///测试out
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Boolean> OutBytesAsync(out System.Byte[] bytes, IInvokeOption invokeOption = default);
}
}
public static class MyRpcServerExtensions
{
///<summary>
///登录
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Boolean Login<TClient>(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;
}
///<summary>
///登录
///</summary>
public static async Task<System.Boolean> LoginAsync<TClient>(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;
}
///<summary>
///注册
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Boolean Register<TClient>(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;
}
///<summary>
///注册
///</summary>
public static async Task<System.Boolean> RegisterAsync<TClient>(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; }
///<summary>
///性能测试
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Int32 Performance<TClient>(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;
}
///<summary>
///性能测试
///</summary>
public static async Task<System.Int32> PerformanceAsync<TClient>(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);
}
///<summary>
///登录
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///测试out
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Boolean OutBytes<TClient>(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;
}
///<summary>
///测试out
///</summary>
public static Task<System.Boolean> OutBytesAsync<TClient>(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<System.Boolean>(returnData);
}
///<summary>
///登录
///</summary>
public async Task<System.Boolean> 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);
}
}
///<summary>
///注册
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;}
}
///<summary>
///注册
///</summary>
public async Task<System.Boolean> 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);
}
///<summary>
///性能测试
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///性能测试
///</summary>
public async Task<System.Int32> 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);
}
///<summary>
///测试out
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///测试out
///</summary>
public Task<System.Boolean> 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<System.Boolean>(returnData);
}
}
public static class MyRpcServerExtensions
{
///<summary>
///登录
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Boolean Login<TClient>(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;
}
///<summary>
///登录
///</summary>
public static async Task<System.Boolean> LoginAsync<TClient>(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);
}
///<summary>
///注册
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Boolean Register<TClient>(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;
}
///<summary>
///注册
///</summary>
public static async Task<System.Boolean> RegisterAsync<TClient>(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);
}
///<summary>
///性能测试
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Int32 Performance<TClient>(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;
}
///<summary>
///性能测试
///</summary>
public static async Task<System.Int32> PerformanceAsync<TClient>(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);
}
///<summary>
///测试out
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Boolean OutBytes<TClient>(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;
}
///<summary>
///测试out
///</summary>
public static Task<System.Boolean> OutBytesAsync<TClient>(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<System.Boolean>(returnData);
}
}
public class RegisterModel
{
public System.String Account { get; set; }
public System.String Password { get; set; }
public System.Int32 Id { get; set; }
}
}

View File

@@ -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
/// <summary>
/// 客户端互相调用Rpc
/// </summary>
static void RunInvokeT_2C()
private static void RunInvokeT_2C()
{
var client1 = GetTcpDmtpClient();
var client2 = GetTcpDmtpClient();
@@ -85,7 +84,7 @@ namespace ClientConsoleApp
/// <summary>
/// 直接调用Rpc
/// </summary>
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<IRpcClient1>();
IRpcClient2 rpcClient2 = client.GetDmtpRpcActor<IRpcClient2>();
var rpcClient1 = client.GetDmtpRpcActor<IRpcClient1>();
var rpcClient2 = client.GetDmtpRpcActor<IRpcClient2>();
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;

View File

@@ -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<MyRpcServer>();
#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}");
}
}
}
}

View File

@@ -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
{
///<summary>
///将两个数相加
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Int32 Add(System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default);
///<summary>
///将两个数相加
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Int32> AddAsync(System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default);
public interface IMyRpcServer : TouchSocket.Rpc.IRemoteServer
{
///<summary>
///将两个数相加
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Int32 Add(System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default);
///<summary>
///测试客户端请求,服务器响应大量流数据
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Int32 RpcPullChannel(System.Int32 channelID,IInvokeOption invokeOption = default);
///<summary>
///测试客户端请求,服务器响应大量流数据
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Int32> RpcPullChannelAsync(System.Int32 channelID,IInvokeOption invokeOption = default);
///<summary>
///将两个数相加
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Int32> AddAsync(System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default);
///<summary>
///测试客户端推送流数据
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Int32 RpcPushChannel(System.Int32 channelID,IInvokeOption invokeOption = default);
///<summary>
///测试客户端推送流数据
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Int32> RpcPushChannelAsync(System.Int32 channelID,IInvokeOption invokeOption = default);
///<summary>
///测试客户端请求,服务器响应大量流数据
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Int32 RpcPullChannel(System.Int32 channelID, IInvokeOption invokeOption = default);
///<summary>
///测试取消调用
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Int32 TestCancellationToken(IInvokeOption invokeOption = default);
///<summary>
///测试取消调用
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<Int32> TestCancellationTokenAsync(IInvokeOption invokeOption = default);
///<summary>
///测试客户端请求,服务器响应大量流数据
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Int32> RpcPullChannelAsync(System.Int32 channelID, IInvokeOption invokeOption = default);
}
public class MyRpcServer :IMyRpcServer
{
public MyRpcServer(IRpcClient client)
{
this.Client=client;
}
public IRpcClient Client{get;private set; }
///<summary>
///将两个数相加
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///将两个数相加
///</summary>
public async Task<System.Int32> 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);
}
///<summary>
///测试客户端推送流数据
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Int32 RpcPushChannel(System.Int32 channelID, IInvokeOption invokeOption = default);
///<summary>
///测试客户端请求,服务器响应大量流数据
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///测试客户端请求,服务器响应大量流数据
///</summary>
public async Task<System.Int32> 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);
}
///<summary>
///测试客户端推送流数据
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Int32> RpcPushChannelAsync(System.Int32 channelID, IInvokeOption invokeOption = default);
///<summary>
///测试客户端推送流数据
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///测试客户端推送流数据
///</summary>
public async Task<System.Int32> 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);
}
///<summary>
///测试取消调用
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Int32 TestCancellationToken(IInvokeOption invokeOption = default);
///<summary>
///测试取消调用
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///测试取消调用
///</summary>
public async Task<Int32> TestCancellationTokenAsync(IInvokeOption invokeOption = default)
{
if(Client==null)
{
throw new RpcException("IRpcClient为空请先初始化或者进行赋值");
}
return (Int32) await Client.InvokeAsync(typeof(Int32),"consoleapp2.myrpcserver.testcancellationtoken",invokeOption, null);
}
///<summary>
///测试取消调用
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<Int32> TestCancellationTokenAsync(IInvokeOption invokeOption = default);
}
}
public static class MyRpcServerExtensions
{
///<summary>
///将两个数相加
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Int32 Add<TClient>(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;
}
///<summary>
///将两个数相加
///</summary>
public static async Task<System.Int32> AddAsync<TClient>(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;
}
///<summary>
///测试客户端请求,服务器响应大量流数据
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Int32 RpcPullChannel<TClient>(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;
}
///<summary>
///测试客户端请求,服务器响应大量流数据
///</summary>
public static async Task<System.Int32> RpcPullChannelAsync<TClient>(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; }
///<summary>
///测试客户端推送流数据
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Int32 RpcPushChannel<TClient>(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;
}
///<summary>
///测试客户端推送流数据
///</summary>
public static async Task<System.Int32> RpcPushChannelAsync<TClient>(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);
}
///<summary>
///将两个数相加
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///测试取消调用
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static Int32 TestCancellationToken<TClient>(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;
}
///<summary>
///测试取消调用
///</summary>
public static async Task<Int32> TestCancellationTokenAsync<TClient>(this TClient client,IInvokeOption invokeOption = default) where TClient:
TouchSocket.Rpc.IRpcClient{
return (Int32) await client.InvokeAsync(typeof(Int32),"consoleapp2.myrpcserver.testcancellationtoken",invokeOption, null);
}
///<summary>
///将两个数相加
///</summary>
public async Task<System.Int32> 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);
}
}
///<summary>
///测试客户端请求,服务器响应大量流数据
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///测试客户端请求,服务器响应大量流数据
///</summary>
public async Task<System.Int32> 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);
}
///<summary>
///测试客户端推送流数据
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///测试客户端推送流数据
///</summary>
public async Task<System.Int32> 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);
}
///<summary>
///测试取消调用
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///测试取消调用
///</summary>
public async Task<Int32> 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
{
///<summary>
///将两个数相加
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Int32 Add<TClient>(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;
}
///<summary>
///将两个数相加
///</summary>
public static async Task<System.Int32> AddAsync<TClient>(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);
}
///<summary>
///测试客户端请求,服务器响应大量流数据
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Int32 RpcPullChannel<TClient>(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;
}
///<summary>
///测试客户端请求,服务器响应大量流数据
///</summary>
public static async Task<System.Int32> RpcPullChannelAsync<TClient>(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);
}
///<summary>
///测试客户端推送流数据
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Int32 RpcPushChannel<TClient>(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;
}
///<summary>
///测试客户端推送流数据
///</summary>
public static async Task<System.Int32> RpcPushChannelAsync<TClient>(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);
}
///<summary>
///测试取消调用
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static Int32 TestCancellationToken<TClient>(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;
}
///<summary>
///测试取消调用
///</summary>
public static async Task<Int32> TestCancellationTokenAsync<TClient>(this TClient client, IInvokeOption invokeOption = default) where TClient :
TouchSocket.Rpc.IRpcClient
{
return (Int32)await client.InvokeAsync(typeof(Int32), "consoleapp2.myrpcserver.testcancellationtoken", invokeOption, null);
}
}
}

View File

@@ -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<MyClassPlugin> 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();
}
}

View File

@@ -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
{
/// <summary>
@@ -59,7 +56,7 @@ namespace FileTransferConsoleApp
/// <summary>
/// 多线程推送文件
/// </summary>
static void MultithreadingClientPushFileFromService()
private static void MultithreadingClientPushFileFromService()
{
using var clientFactory = CreateClientFactory();
var resultCon = clientFactory.CheckStatus();//检验连接状态,一般当主通行器连接时,即认为在连接状态。
@@ -126,7 +123,7 @@ namespace FileTransferConsoleApp
/// <summary>
/// 多线程请求文件
/// </summary>
static void MultithreadingClientPullFileFromService()
private static void MultithreadingClientPullFileFromService()
{
using var clientFactory = CreateClientFactory();
var resultCon = clientFactory.CheckStatus();//检验连接状态,一般当主通行器连接时,即认为在连接状态。
@@ -192,7 +189,7 @@ namespace FileTransferConsoleApp
/// 推送小文件
/// </summary>
/// <param name="client"></param>
static void PushSmallFileFromService(TcpDmtpClient client)
private static void PushSmallFileFromService(TcpDmtpClient client)
{
ConsoleLogger.Default.Info("开始从服务器下载小文件");
var filePath = "PushSmallFileFromService.Test";
@@ -228,7 +225,7 @@ namespace FileTransferConsoleApp
/// 请求小文件
/// </summary>
/// <param name="client"></param>
static void PullSmallFileFromService(TcpDmtpClient client)
private static void PullSmallFileFromService(TcpDmtpClient client)
{
ConsoleLogger.Default.Info("开始从服务器下载小文件");
@@ -269,7 +266,7 @@ namespace FileTransferConsoleApp
/// <summary>
/// 客户端向其他客户端推送文件。
/// </summary>
static void ClientPushFileFromClient()
private static void ClientPushFileFromClient()
{
using var client1 = GetTcpDmtpClient();
using var client2 = GetTcpDmtpClient();
@@ -330,7 +327,7 @@ namespace FileTransferConsoleApp
/// <summary>
/// 客户端从其他客户端下载文件。
/// </summary>
static void ClientPullFileFromClient()
private static void ClientPullFileFromClient()
{
using var client1 = GetTcpDmtpClient();
using var client2 = GetTcpDmtpClient();
@@ -393,7 +390,7 @@ namespace FileTransferConsoleApp
/// </summary>
/// <param name="service">服务器</param>
/// <param name="targetId">服务器要请求的客户端Id</param>
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
/// </summary>
/// <param name="service">服务器</param>
/// <param name="targetId">服务器要请求的客户端Id</param>
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
/// 客户端从服务器下载文件。
/// </summary>
/// <param name="client"></param>
static void ClientPullFileFromService(TcpDmtpClient client)
private static void ClientPullFileFromService(TcpDmtpClient client)
{
ConsoleLogger.Default.Info("开始从服务器下载文件");
@@ -605,7 +602,7 @@ namespace FileTransferConsoleApp
/// 客户端上传文件到服务器。
/// </summary>
/// <param name="client"></param>
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;
@@ -839,5 +834,4 @@ namespace FileTransferConsoleApp
await e.InvokeNext();
}
}
}

View File

@@ -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()//配置

View File

@@ -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,7 +11,7 @@ namespace RealityProxyDmtpRpcConsoleApp
/// </summary>
internal class Program
{
static void Main(string[] args)
private static void Main(string[] args)
{
var myDmtpRpcRealityProxy = new MyDmtpRpcRealityProxy<IMyRpcServer>();
@@ -27,7 +27,7 @@ namespace RealityProxyDmtpRpcConsoleApp
/// 新建一个类按照需要继承DmtpRpcRealityProxy亦或者RpcRealityProxy基类。
/// 然后实现抽象方法主要是能获取到调用的IRpcClient派生接口。
/// </summary>
class MyDmtpRpcRealityProxy<T> : DmtpRpcRealityProxy<T>
internal class MyDmtpRpcRealityProxy<T> : DmtpRpcRealityProxy<T>
{
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
{
/// <summary>
/// 将两个数相加

View File

@@ -1,5 +1,4 @@
using RpcImplementationClassLibrary;
using TouchSocket.Core;
using TouchSocket.Core;
using TouchSocket.Dmtp;
using TouchSocket.Dmtp.Rpc;
using TouchSocket.Rpc;

View File

@@ -52,7 +52,6 @@ namespace RemoteStreamConsoleApp
{
Console.ReadKey();
}
}
private static TcpDmtpClient GetTcpDmtpClient()

View File

@@ -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
/// <summary>
/// 定义请求包
/// </summary>
class MyRequestPackage : DmtpRouterPackage
private class MyRequestPackage : DmtpRouterPackage
{
/// <summary>
/// 包尺寸大小。此值并非需要精准数值,只需要估计数据即可。其作用为申请内存池。所以数据应当大小合适。
@@ -159,7 +158,7 @@ namespace RouterPackageConsoleApp
/// <summary>
/// 定义响应包
/// </summary>
class MyResponsePackage : DmtpRouterPackage
private class MyResponsePackage : DmtpRouterPackage
{
/// <summary>
/// 包尺寸大小。此值并非需要精准数值,只需要估计数据即可。其作用为申请内存池。所以数据应当大小合适。
@@ -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();
}

View File

@@ -1,6 +1,5 @@
using RpcClassLibrary.Models;
using RpcClassLibrary.ServerInterface;
using System;
using TouchSocket.Core;
using TouchSocket.Rpc;

View File

@@ -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
{
}
}

View File

@@ -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

View File

@@ -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();
}

View File

@@ -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 {

View File

@@ -96,8 +96,5 @@
dt.getSeconds() + "秒";
});
</script>
</body>
</html>

View File

@@ -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()//加载配置

View File

@@ -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<IJsonRpcServer, MyJsonRpcDispatchProxy>();
@@ -24,7 +22,7 @@ namespace DispatchProxyJsonRpcClientConsoleApp
/// 新建一个类继承JsonRpcDispatchProxy亦或者RpcDispatchProxy基类。
/// 然后实现抽象方法主要是能获取到调用的IRpcClient派生接口。
/// </summary>
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);

View File

@@ -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;

View File

@@ -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
{
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.String TestGetContext(System.String str,IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.String> TestGetContextAsync(System.String str,IInvokeOption invokeOption = default);
public interface IJsonRpcServer : TouchSocket.Rpc.IRemoteServer
{
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.String TestGetContext(System.String str, IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Newtonsoft.Json.Linq.JObject TestJObject(Newtonsoft.Json.Linq.JObject obj,IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<Newtonsoft.Json.Linq.JObject> TestJObjectAsync(Newtonsoft.Json.Linq.JObject obj,IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.String> TestGetContextAsync(System.String str, IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.String TestJsonRpc(System.String str,IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.String> TestJsonRpcAsync(System.String str,IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Newtonsoft.Json.Linq.JObject TestJObject(Newtonsoft.Json.Linq.JObject obj, IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.String Show(System.Int32 a,System.Int32 b,System.Int32 c,IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.String> ShowAsync(System.Int32 a,System.Int32 b,System.Int32 c,IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<Newtonsoft.Json.Linq.JObject> 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; }
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<System.String> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.String TestJsonRpc(System.String str, IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<Newtonsoft.Json.Linq.JObject> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.String> TestJsonRpcAsync(System.String str, IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<System.String> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.String Show(System.Int32 a, System.Int32 b, System.Int32 c, IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<System.String> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.String> ShowAsync(System.Int32 a, System.Int32 b, System.Int32 c, IInvokeOption invokeOption = default);
}
}
public static class JsonRpcServerExtensions
{
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.String TestGetContext<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.String> TestGetContextAsync<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static Newtonsoft.Json.Linq.JObject TestJObject<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<Newtonsoft.Json.Linq.JObject> TestJObjectAsync<TClient>(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; }
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.String TestJsonRpc<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.String> TestJsonRpcAsync<TClient>(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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.String Show<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.String> ShowAsync<TClient>(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);
}
///<summary>
///无注释信息
///</summary>
public async Task<System.String> 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);
}
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<Newtonsoft.Json.Linq.JObject> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<System.String> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<System.String> 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
{
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.String TestGetContext<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.String> TestGetContextAsync<TClient>(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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static Newtonsoft.Json.Linq.JObject TestJObject<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<Newtonsoft.Json.Linq.JObject> TestJObjectAsync<TClient>(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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.String TestJsonRpc<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.String> TestJsonRpcAsync<TClient>(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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.String Show<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.String> ShowAsync<TClient>(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);
}
}
}

View File

@@ -112,8 +112,6 @@ namespace JsonRpcConsoleApp
}));
service.Start();
}
}
public partial class JsonRpcServer : RpcServer

View File

@@ -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<IHttpSocketClient>
internal class MyPluginClass : PluginBase, IWebSocketHandshakedPlugin<IWebSocket>
{
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<int>("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();
}
}

View File

@@ -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<MyClass>(SerializationType.Json).ToJsonString());
}
/// <summary>
@@ -151,7 +150,7 @@ namespace ModbusClientConsoleApp
}
}
class MyClass
internal class MyClass
{
public int P1 { get; set; }
public int P2 { get; set; }

View File

@@ -6,7 +6,7 @@ namespace ModbusObjectConsoleApp
{
internal class Program
{
static void Main(string[] args)
private static void Main(string[] args)
{
try
{
@@ -44,7 +44,7 @@ namespace ModbusObjectConsoleApp
/// Tcp从站
/// </summary>
/// <returns></returns>
static ModbusTcpSlave CreateModbusTcpSlave()
private static ModbusTcpSlave CreateModbusTcpSlave()
{
var service = new ModbusTcpSlave();
service.Setup(new TouchSocketConfig()
@@ -83,9 +83,10 @@ namespace ModbusObjectConsoleApp
}
}
class MyModbusObject : ModbusObject
internal class MyModbusObject : ModbusObject
{
#region Coils
/// <summary>
/// 声明一个来自线圈的bool属性。
/// <para>
@@ -111,9 +112,11 @@ namespace ModbusObjectConsoleApp
get { return this.GetValueArray<bool>(); }
set { this.SetValueArray(value); }
}
#endregion
#endregion Coils
#region DiscreteInputs
/// <summary>
/// 声明一个来自离散输入的bool属性。
/// <para>
@@ -137,9 +140,11 @@ namespace ModbusObjectConsoleApp
{
get { return this.GetValue<bool>(); }
}
#endregion
#endregion DiscreteInputs
#region HoldingRegisters
/// <summary>
/// 声明一个来自保持寄存器的short属性。
/// <para>
@@ -165,9 +170,11 @@ namespace ModbusObjectConsoleApp
get { return this.GetValueArray<short>(); }
set { this.SetValueArray(value); }
}
#endregion
#endregion HoldingRegisters
#region InputRegisters
/// <summary>
/// 声明一个来自输入寄存器的short属性。
/// <para>
@@ -191,6 +198,7 @@ namespace ModbusObjectConsoleApp
{
get { return this.GetValueArray<short>(); }
}
#endregion
#endregion InputRegisters
}
}

View File

@@ -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)
{

View File

@@ -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 =>
{

View File

@@ -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();
}

View File

@@ -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))

View File

@@ -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) };

View File

@@ -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<MyRpcServer>();//注册服务
});
a.AddRateLimiter(p =>
{
//添加一个名称为FixedWindow的固定窗口的限流策略

View File

@@ -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<MyPlugin>();
@@ -61,7 +61,7 @@ namespace SerialPortClientConsoleApp
}
}
class MyClassPlugin : PluginBase, ISerialConnectedPlugin
internal class MyClassPlugin : PluginBase, ISerialConnectedPlugin
{
public async Task OnSerialConnected(ISerialPortClient client, ConnectedEventArgs e)
{
@@ -75,8 +75,8 @@ 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;//表示该数据已经被本插件处理,无需再投递到其他插件。

View File

@@ -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<ISocketClient>,ITcpDisconnectedPlugin<ISocketClient>,ITcpReceivedPlugin<ISocketClient>
internal class MyClassPlugin : PluginBase, ITcpConnectedPlugin<ISocketClient>, ITcpDisconnectedPlugin<ISocketClient>, ITcpReceivedPlugin<ISocketClient>
{
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()}");

View File

@@ -23,7 +23,7 @@ namespace TcpCommandLineConsoleApp
.ConfigurePlugins(a =>
{
a.UseCheckClear()
.SetCheckClearType( CheckClearType.All)
.SetCheckClearType(CheckClearType.All)
.SetTick(TimeSpan.FromSeconds(60));
a.Add<MyCommandLinePlugin>();

View File

@@ -21,7 +21,6 @@ namespace ServiceConsoleApp
consoleAction.RunCommandLine();
}
private static TcpService CreateService()
{
var service = new TcpService();
@@ -50,7 +49,6 @@ namespace ServiceConsoleApp
return service;
}
/// <summary>
/// 以Received异步委托接收数据
/// </summary>
@@ -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<ISocketClient>
internal class TcpServiceReceiveAsyncPlugin : PluginBase, ITcpConnectedPlugin<ISocketClient>
{
public async Task OnTcpConnected(ISocketClient client, ConnectedEventArgs e)
{
@@ -195,14 +190,13 @@ namespace ServiceConsoleApp
client.Logger.Info($"客户端接收到信息:{mes}");
//如果是适配器信息则可以直接获取receiverResult.RequestInfo;
}
}
}
}
}
class TcpServiceReceivedPlugin : PluginBase, ITcpReceivedPlugin<ISocketClient>
internal class TcpServiceReceivedPlugin : PluginBase, ITcpReceivedPlugin<ISocketClient>
{
public async Task OnTcpReceived(ISocketClient client, ReceivedDataEventArgs e)
{
@@ -235,7 +229,7 @@ namespace ServiceConsoleApp
/// <summary>
/// 应一个网友要求,该插件主要实现,在接收数据时如果触发<see cref="CloseException"/>异常,则断开连接。
/// </summary>
class ClosePlugin : PluginBase, ITcpReceivedPlugin<ISocketClient>
internal class ClosePlugin : PluginBase, ITcpReceivedPlugin<ISocketClient>
{
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)
{
}
}
}

View File

@@ -11,7 +11,7 @@ namespace TcpWaitingClientWinFormsApp
this.InitializeComponent();
}
TcpClient m_tcpClient;
private TcpClient m_tcpClient;
private void IsConnected()
{

View File

@@ -9,7 +9,7 @@ namespace TcpWaitingClientWinFormsApp
/// The main entry point for the application.
/// </summary>
[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("<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>");
}
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($"<22>յ<EFBFBD><D5B5><EFBFBD><EFBFBD>ݣ<EFBFBD>{e.ByteBlock.ToString()}");

View File

@@ -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)
{

View File

@@ -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("等待接收");
}

View File

@@ -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)
{

View File

@@ -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();

View File

@@ -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<ISocketClient>, ITcpDisconnectedPlugin<ISocketClient>, ITcpReceivedPlugin<ISocketClient>
{
public async Task OnTcpConnected(ISocketClient client, ConnectedEventArgs e)
{
client.Logger.Info($"客户端{client.GetInfo()}已连接");

View File

@@ -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
{
///<summary>
///登录
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
MyLoginModelResult Login(MyLoginModel model,IInvokeOption invokeOption = default);
///<summary>
///登录
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<MyLoginModelResult> LoginAsync(MyLoginModel model,IInvokeOption invokeOption = default);
public interface IMyRpcServer : TouchSocket.Rpc.IRemoteServer
{
///<summary>
///登录
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
MyLoginModelResult Login(MyLoginModel model, IInvokeOption invokeOption = default);
///<summary>
///性能测试
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Int32 Performance(System.Int32 i,IInvokeOption invokeOption = default);
///<summary>
///性能测试
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Int32> PerformanceAsync(System.Int32 i,IInvokeOption invokeOption = default);
///<summary>
///登录
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<MyLoginModelResult> LoginAsync(MyLoginModel model, IInvokeOption invokeOption = default);
}
public class MyRpcServer :IMyRpcServer
{
public MyRpcServer(IRpcClient client)
{
this.Client=client;
}
public IRpcClient Client{get;private set; }
///<summary>
///登录
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///登录
///</summary>
public async Task<MyLoginModelResult> 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);
}
///<summary>
///性能测试
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Int32 Performance(System.Int32 i, IInvokeOption invokeOption = default);
///<summary>
///性能测试
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///性能测试
///</summary>
public async Task<System.Int32> 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);
}
///<summary>
///性能测试
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Int32> PerformanceAsync(System.Int32 i, IInvokeOption invokeOption = default);
}
}
public static class MyRpcServerExtensions
{
///<summary>
///登录
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static MyLoginModelResult Login<TClient>(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;
}
///<summary>
///登录
///</summary>
public static async Task<MyLoginModelResult> LoginAsync<TClient>(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;
}
///<summary>
///性能测试
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Int32 Performance<TClient>(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;
}
///<summary>
///性能测试
///</summary>
public static async Task<System.Int32> PerformanceAsync<TClient>(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; }
}
///<summary>
///登录
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;}
}
///<summary>
///登录
///</summary>
public async Task<MyLoginModelResult> 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);
}
///<summary>
///性能测试
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;}
}
///<summary>
///性能测试
///</summary>
public async Task<System.Int32> 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
{
///<summary>
///登录
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static MyLoginModelResult Login<TClient>(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;
}
///<summary>
///登录
///</summary>
public static async Task<MyLoginModelResult> LoginAsync<TClient>(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);
}
///<summary>
///性能测试
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Int32 Performance<TClient>(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;
}
///<summary>
///性能测试
///</summary>
public static async Task<System.Int32> PerformanceAsync<TClient>(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; }
}
}

View File

@@ -10,16 +10,16 @@ namespace DispatchProxyWebApiConsoleApp
/// 使用DispatchProxy生成调用代理
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
private static void Main(string[] args)
{
var api = MyWebApiDispatchProxy.Create<IApiServer, MyWebApiDispatchProxy>();
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派生接口。
/// </summary>
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]")]

View File

@@ -45,7 +45,6 @@ namespace WebApiClientApp
Console.WriteLine($"代理调用成功,结果:{sum3}");
}
Console.ReadKey();
}
@@ -78,7 +77,7 @@ namespace WebApiClientApp
/// <summary>
/// 此处可以做WebApi的请求之前和之后的拦截。
/// </summary>
class MyWebApiPlugin : PluginBase, IWebApiPlugin<IWebApiClientBase>
private class MyWebApiPlugin : PluginBase, IWebApiPlugin<IWebApiClientBase>
{
public async Task OnRequest(IWebApiClientBase client, WebApiEventArgs e)
{

View File

@@ -176,12 +176,12 @@ namespace WebApiServerApp
[WebApi(HttpMethodType.POST)]
public Task<string> 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
/// <summary>
/// 鉴权插件
/// </summary>
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<string, HttpContext>
internal class MySerializerFormatter : ISerializerFormatter<string, HttpContext>
{
public int Order { get; set; }

View File

@@ -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
{
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Int32 Sum(System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Int32> SumAsync(System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default);
public interface IApiServer : TouchSocket.Rpc.IRemoteServer
{
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Int32 Sum(System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
MyClass GetMyClass(IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<MyClass> GetMyClassAsync(IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Int32> SumAsync(System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Int32 TestPost(MyClass myClass,IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Int32> TestPostAsync(MyClass myClass,IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
MyClass GetMyClass(IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.String DownloadFile(System.String id,IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.String> DownloadFileAsync(System.String id,IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<MyClass> GetMyClassAsync(IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.String PostContent(IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.String> PostContentAsync(IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Int32 TestPost(MyClass myClass, IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.String UploadMultiFile(System.String id,IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.String> UploadMultiFileAsync(System.String id,IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Int32> TestPostAsync(MyClass myClass, IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.String UploadBigFile(IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.String> UploadBigFileAsync(IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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; }
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<System.Int32> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.String> DownloadFileAsync(System.String id, IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<MyClass> GetMyClassAsync(IInvokeOption invokeOption = default)
{
if(Client==null)
{
throw new RpcException("IRpcClient为空请先初始化或者进行赋值");
}
return (MyClass) await Client.InvokeAsync(typeof(MyClass),"GET:/apiserver/getmyclass",invokeOption, null);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.String PostContent(IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<System.Int32> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.String> PostContentAsync(IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<System.String> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.String UploadMultiFile(System.String id, IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<System.String> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.String> UploadMultiFileAsync(System.String id, IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<System.String> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.String UploadBigFile(IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<System.String> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.String> UploadBigFileAsync(IInvokeOption invokeOption = default);
}
}
public static class ApiServerExtensions
{
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Int32 Sum<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.Int32> SumAsync<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static MyClass GetMyClass<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<MyClass> GetMyClassAsync<TClient>(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; }
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Int32 TestPost<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.Int32> TestPostAsync<TClient>(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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.String DownloadFile<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.String> DownloadFileAsync<TClient>(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);
}
///<summary>
///无注释信息
///</summary>
public async Task<System.Int32> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.String PostContent<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.String> PostContentAsync<TClient>(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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.String UploadMultiFile<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.String> UploadMultiFileAsync<TClient>(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);
}
///<summary>
///无注释信息
///</summary>
public async Task<MyClass> GetMyClassAsync(IInvokeOption invokeOption = default)
{
if (Client == null)
{
throw new RpcException("IRpcClient为空请先初始化或者进行赋值");
}
return (MyClass)await Client.InvokeAsync(typeof(MyClass), "GET:/apiserver/getmyclass", invokeOption, null);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.String UploadBigFile<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.String> UploadBigFileAsync<TClient>(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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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; }
}
///<summary>
///无注释信息
///</summary>
public async Task<System.Int32> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<System.String> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<System.String> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<System.String> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<System.String> 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
{
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Int32 Sum<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.Int32> SumAsync<TClient>(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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static MyClass GetMyClass<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<MyClass> GetMyClassAsync<TClient>(this TClient client, IInvokeOption invokeOption = default) where TClient :
TouchSocket.WebApi.IWebApiClientBase
{
return (MyClass)await client.InvokeAsync(typeof(MyClass), "GET:/apiserver/getmyclass", invokeOption, null);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Int32 TestPost<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.Int32> TestPostAsync<TClient>(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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.String DownloadFile<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.String> DownloadFileAsync<TClient>(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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.String PostContent<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.String> PostContentAsync<TClient>(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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.String UploadMultiFile<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.String> UploadMultiFileAsync<TClient>(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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.String UploadBigFile<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.String> UploadBigFileAsync<TClient>(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; }
}
}

View File

@@ -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)
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)
{
break;
}
if (receiveResult.DataFrame==null)
//判断是否为最后数据
//例如发送方发送了一个10Mb的数据接收时可能会多次接收所以需要此属性判断。
if (receiveResult.DataFrame.FIN)
{
if (receiveResult.DataFrame.IsText)
{
break;
this.m_logger.Info($"WebSocket文本{receiveResult.DataFrame.ToText()}");
}
//判断是否为最后数据
//例如发送方发送了一个10Mb的数据接收时可能会多次接收所以需要此属性判断。
if (receiveResult.DataFrame.FIN)
{
if (receiveResult.DataFrame.IsText)
{
m_logger.Info($"WebSocket文本{receiveResult.DataFrame.ToText()}");
}
}
}
}
//此处即表明websocket已断开连接
m_logger.Info("WebSocket断开连接");
}
//此处即表明websocket已断开连接
this.m_logger.Info("WebSocket断开连接");
await e.InvokeNext();
}
}

View File

@@ -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<IHttpClientBase, StringBuilder> m_stringBuilders = new Dictionary<IHttpClientBase, StringBuilder>();//接收临时Text
private Dictionary<IWebSocket, StringBuilder> m_stringBuilders = new Dictionary<IWebSocket, StringBuilder>();//接收临时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<IHttpSocketClient>
private class MyHttpPlugin : PluginBase, IHttpPlugin<IHttpSocketClient>
{
public async Task OnHttpRequest(IHttpSocketClient client, HttpContextEventArgs e)
{

View File

@@ -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<IXmlRpcServer, MyXmlRpcDispatchProxy>();
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派生接口。
/// </summary>
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);

View File

@@ -40,9 +40,8 @@ namespace XmlRpcServerApp
Console.ReadKey();
}
static void a()
private static void a()
{
}
}

View File

@@ -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
{
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Int32 Sum(System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Int32> SumAsync(System.Int32 a,System.Int32 b,IInvokeOption invokeOption = default);
public interface IXmlServer : TouchSocket.Rpc.IRemoteServer
{
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Int32 Sum(System.Int32 a, System.Int32 b, IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Int32 TestClass(MyClass myClass,IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Int32> TestClassAsync(MyClass myClass,IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Int32> 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; }
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<System.Int32> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
System.Int32 TestClass(MyClass myClass, IInvokeOption invokeOption = default);
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<System.Int32> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
Task<System.Int32> TestClassAsync(MyClass myClass, IInvokeOption invokeOption = default);
}
}
public static class XmlServerExtensions
{
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Int32 Sum<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.Int32> SumAsync<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Int32 TestClass<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.Int32> TestClassAsync<TClient>(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; }
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;}
}
///<summary>
///无注释信息
///</summary>
public async Task<System.Int32> 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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
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;
}
///<summary>
///无注释信息
///</summary>
public async Task<System.Int32> 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
{
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Int32 Sum<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.Int32> SumAsync<TClient>(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);
}
///<summary>
///无注释信息
///</summary>
/// <exception cref="System.TimeoutException">调用超时</exception>
/// <exception cref="TouchSocket.Rpc.RpcInvokeException">Rpc调用异常</exception>
/// <exception cref="System.Exception">其他异常</exception>
public static System.Int32 TestClass<TClient>(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;
}
///<summary>
///无注释信息
///</summary>
public static async Task<System.Int32> TestClassAsync<TClient>(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; }
}
}

View File

@@ -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`有自己的PingPong机制。所以直接调用已有方法即可。
`WebSocket`有自己的`Ping`、`Pong`机制。所以直接调用已有方法即可。
```csharp showLineNumbers
client.PingWS();
client.PongWS();
client.Ping();
client.Pong();
```
:::tip 建议
WebSocket是双向通讯所以支持客户端和服务器双向操作PingPong报文。但是一般来说都是客户端执行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)

View File

@@ -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 验证连接
可以对连接的UrlQueryHeader等参数进行验证然后决定是否执行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<IHttpSocketClient>
class MyHttpPlugin : PluginBase, IHttpPlugin<IHttpSocketClient>
{
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<IHttpSocketClient>
### 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("广播");
}
}
```