当前位置:网站首页>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
边栏推荐
- . net tip: talk about the problem that the scoped service cannot be obtained in the middleware structure
- [authentication / authorization] customize an authentication handler
- [Mysql] LEFT函數 | RIGHT函數
- PID debugging of coding motor (speed loop | position loop | follow)
- Experiment 5 components and event handling
- Idempotency practice operation, explaining idempotency based on business
- C语言实现通讯录----(静态版本)
- Top 9 task management system in 2022
- Iotos IOT middle platform is connected to the access control system of isecure center
- socket編程 send()與 recv()函數詳解
猜你喜欢

Fight leetcode again (290. Word law)

Peut recevoir plusieurs paramètres de type de données - paramètres variables

IDEA查看历史记录【文件历史和项目历史】

Impact of AOT and single file release on program performance

Mise en service PID du moteur de codage (anneau de vitesse | anneau de position | suivant)

Utgard connection opcserver reported an error caused by: org jinterop. dcom. common. JIRuntimeException: Access is denied. [0x800

关于idea调试模式下启动特别慢的优化

【VS Code】解决jupyter文件在vs code中显示异常的问题

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

研讨会回放视频:如何提升Jenkins能力,使其成为真正的DevOps平台
随机推荐
Huawei mobile ADB devices connection device is empty
TCP three handshakes and four waves
Mysql database design specification
Scenario Title: how does system a use the page of system B
Find the number of leaf nodes of binary tree
队列的存储和循环队列
2022g2 boiler stoker examination question bank and online simulation examination
LoadRunner - performance testing tool
ASP. Net and ASP NETCORE multi environment configuration comparison
After the mobile phone is connected to the computer, how can QT's QDIR read the mobile phone file path
yes. Net future
oracle 查询外键含有逗号分隔的数据
How to achieve centralized management, flexible and efficient CI / CD online seminar highlights sharing
2022a special equipment related management (elevator) work license question bank and simulation examination
Configuration table and page information automatically generate curd operation page
How does Microsoft solve the problem of multiple PC programs
EasyUI's combobox implements three-level query
Flink real-time data warehouse project - Design and implementation of DWS layer
2022A特种设备相关管理(电梯)上岗证题库及模拟考试
Chapter 9 of C language programming (fifth edition of Tan Haoqiang) analysis and answer of exercises for users to establish their own data types