当前位置:网站首页>Supersocket is Used in net5 - command
Supersocket is Used in net5 - command
2022-04-23 03:18:00 【Pingshan CP3】
background :Command Take out the command list and learn , In fact, it's just because it depends on your usage habits , If you don't want to use the built-in logic to process the message , You can do it yourself UsePackageHandler Method ; Or your TReceivePackage Package type does not inherit IKeyedPackageInfo<T>, There's no need to build in at this time Command Processing logic .
Of course ,Command And the use of filters still has many advantages , Make your business processing code more concise and clear , Make your code structure clearer , You can use filters to monitor business processing and add some processing isolated from business processing code ; Next, let's learn Command How to use it?
Now start the scenario defined in the article , Now create a Command To handle accepting and adding (Add) Business operations of user commands ; Data structures and filters are the same as above “ Startup ” In the same , But it should be noted that the data structure class should inherit IKeyedPackageInfo<T>
The message received is so long :
1. The new name is Add Of Command
[Command(Key = "add")]
public class Add : IAsyncCommand<MyPackage>
{
public async ValueTask ExecuteAsync(IAppSession session, MyPackage package)
{
//TODO Your business
string sql = $" insert into Users(UserName) values ('{package.UserName}')";
Thread.Sleep(1000);
await session.SendAsync(Encoding.UTF8.GetBytes(package.UserName));
}
}
Here's the thing to notice :
(1). characteristic Key There can be no , In no case Command The route of is according to key and Command Name to match
(2). Appoint Comand Of key When , Just press key, Can't press Command Name to match
2. register Command
What we should pay attention to here is , Use Command To handle business , It can't be used anymore UsePackageHandler The method , Because use UsePackageHandler Will overwrite Command Related methods
var host = SuperSocketHostBuilder.Create<MyPackage, MyFilter>()
//.UsePackageHandler(async (s, p) =>
//{
// // handle your package over here
// await s.SendAsync(Encoding.UTF8.GetBytes(p.Key + "\r\n"));
//})
.UseCommand((commandOptions) =>
{
// Register the add user command
commandOptions.AddCommand<Add>();
//...add else command
})
.Build();
await host.RunAsync();
Now you can test :
Find out key yes “add” when , Will execute Add( Created Command) The asynchronous method inside ExecuteAsync
3. Next, add Command Filter,Command Filter Equivalent to ASP.MVC Medium AOP Action filter , Will be called before or after the command is executed .
New inheritance AsyncCommandFilterAttribute perhaps CommandFilterAttribute Of CommandFilter
/// <summary>
/// Command filter
/// </summary>
public class AddCommandFilterAttribute : CommandFilterAttribute
{
public override void OnCommandExecuted(CommandExecutingContext commandContext)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+" After adding users ");
}
public override bool OnCommandExecuting(CommandExecutingContext commandContext)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Before adding users ");
return true;
}
}
/// <summary>
/// asynchronous Command filter
/// </summary>
public class AsyncAddCommandFilterAttribute : AsyncCommandFilterAttribute
{
public override async ValueTask OnCommandExecutedAsync(CommandExecutingContext commandContext)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " After adding users Async");
await Task.Delay(0);
}
public override async ValueTask<bool> OnCommandExecutingAsync(CommandExecutingContext commandContext)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Before adding users Async");
await Task.Delay(0);
return true;
}
}
Add a property to the appropriate Command On :
The test results :
There are also global filters , Is defined in all Command What needs to be done before and after the execution of , The order of execution is specified elsewhere Filter Before
public class AsyncMyGlobalFiterAttribute : AsyncCommandFilterAttribute
{
public override async ValueTask OnCommandExecutedAsync(CommandExecutingContext commandContext)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " After processing the message Async");
await Task.Delay(0);
}
public override async ValueTask<bool> OnCommandExecutingAsync(CommandExecutingContext commandContext)
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Before processing the message Async");
await Task.Delay(0);
string commandName = commandContext.CurrentCommand.ToString();
MyPackage myPackage = (MyPackage)commandContext.Package;
if (myPackage.UserName == "Admin")
{
// For example, the user name is Admin Not when Command Handle
return false;
}
return true;
}
}
Register global filter
.UseCommand((commandOptions) =>
{
// Register the add user command
commandOptions.AddCommand<Add>();
//...add else command
// Register global filter
commandOptions.AddGlobalCommandFilter<AsyncMyGlobalFiterAttribute>();
})
test
SuperSocket.Core Medium Command That's what I learned
版权声明
本文为[Pingshan CP3]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220627116777.html
边栏推荐
- TCP three handshakes and four waves
- Idea view history [file history and project history]
- C syntax pattern matching [switch expression]
- Generate QR code through zxing
- Fight leetcode again (290. Word law)
- 《C语言程序设计》(谭浩强第五版) 第7章 用函数实现模块化程序设计 习题解析与答案
- Tencent video price rise: earn more than 7.4 billion a year! Pay attention to me to receive Tencent VIP members, and the weekly card is as low as 7 yuan
- JS implementation of new
- 搭建XAMPP时mysql端口被占用
- Xutils3 corrected a bug I reported. Happy
猜你喜欢
一套组合拳,打造一款 IDEA 护眼方案
Web Course Design - his system
Experiment 5 components and event handling
OLED multi-level menu record
Xutils3 corrected a bug I reported. Happy
LoadRunner - performance testing tool
OLED多级菜单记录
Chapter 7 of C language programming (fifth edition of Tan Haoqiang) analysis and answer of modular programming exercises with functions
Use of ADB command [1]
Xamarin effect Chapter 22 recording effect
随机推荐
Experiment 5 components and event handling
Advanced sorting - fast sorting
Node configuration environment CMD does not take effect
Utgard connection opcserver reported an error caused by: org jinterop. dcom. common. JIRuntimeException: Access is denied. [0x800
Experiment 6 input / output stream
Docker拉取mysql并连接
Preview of converting doc and PDF to SWF file
Student achievement management
JS implementation of new
Find the number of leaf nodes of binary tree
Chapter 9 of C language programming (fifth edition of Tan Haoqiang) analysis and answer of exercises for users to establish their own data types
The website JS in. Net core cefsharp chromium WebBrowser calls the C method in winfrom program
月薪10k-20k都无法回答的事务问题,你会吗?
Mise en service PID du moteur de codage (anneau de vitesse | anneau de position | suivant)
Idea view history [file history and project history]
Mysql database, inconsistent index character set, slow SQL query, interface timeout
2022A特种设备相关管理(电梯)上岗证题库及模拟考试
12. < tag linked list and common test site synthesis > - lt.234 palindrome linked list
ASP. Net and ASP NETCORE multi environment configuration comparison
OLED multi-level menu record