当前位置:网站首页>Supersocket is Use in net5 - startup
Supersocket is Use in net5 - startup
2022-04-23 03:18:00 【Pingshan CP3】
background : The basic concepts are introduced above , Compared with the official website, it is not complete , But it is also a basic concept that can be used . This article continues from the start SuperSocket The angle of , Continue to introduce the use of SuperSocket
1. Two ways to start
(1) General startup mode , In any .net5 Can be used in programs
public static async Task Main(string[] args)
{
var host = SuperSocketHostBuilder.Create<TextPackageInfo, LinePipelineFilter>()
.UsePackageHandler(async (s, p) => {
// Conduct business processing on the received data , And you can choose whether to feed back to the client data
await s.SendAsync(Encoding.UTF8.GetBytes(p + "\r\n"));
})
.Build();
// start-up SuperSocketHostBuilder
await host.RunAsync();
}
The above lines of code can start a simple Server:
(2) stay .Net Core Web Start in , In this way, you can be in a Web Website or WebApi Start one at the same time Socket Server
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.AsSuperSocketHostBuilder<TextPackageInfo, LinePipelineFilter>()
.UsePackageHandler(async (s, p) =>
{
// Conduct business processing on the received data , And you can choose whether to feed back to the client data
await s.SendAsync(Encoding.UTF8.GetBytes(p + "\r\n"));
});
2. Two configurations
stay SuperSocket in , You can target Server Set properties , And easily open multiple Server
(1)“ Concept ” Has been introduced in SuperSocket Configuration file for , By means of appsettings.json Add serverOptions Node to configure Server Options , And start monitoring multiple Server
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"serverOptions": {
"name": "TestServer",
"listeners": [
{
"ip": "127.0.0.1",
"port": 4040,
"sendTimeout": 20000,
"maxPackageLength": 2048
},
{
"ip": "Any",
"port": 4041
}
]
},
"AllowedHosts": "*"
}
The above configuration items listen to the of this machine at the same time 4040 and 4041 port
(2) adopt ConfigureSuperSocket Method configuration requires
var host = SuperSocketHostBuilder.Create<TextPackageInfo, LinePipelineFilter>()
.ConfigureSuperSocket(options =>
{
// To configure SuperSocket Options
options.Name = "TestServer";
options.ReceiveBufferSize = 2048;
options.SendTimeout = 20000;
options.Listeners = new List<ListenOptions>(){
new ListenOptions{
Ip="Any",
Port = 4042
}
};
})
.UsePackageHandler(async (s, p) =>
{
// Conduct business processing on the received data , And you can choose whether to feed back to the client data
await s.SendAsync(Encoding.UTF8.GetBytes(p + "\r\n"));
})
.Build();
It should be noted that , This will overwrite the information about... In the configuration file SuperSocket Configuration options .
3. Use filters
Through the use of built-in filters and custom filters and further introduction SuperSocket in Filter Use
(1) Using built-in filters FixedSizePipelineFilter
public class MyFixedSizePipelineFilter : FixedSizePipelineFilter<StringPackageInfo>
{
// Specify a length of 15 Filters for valid data
public MyFixedSizePipelineFilter() : base(15)
{
}
}
Filter binding SuperSocket
var host = SuperSocketHostBuilder.Create<StringPackageInfo, MyFixedSizePipelineFilter>()
.ConfigureSuperSocket(options =>
{
// To configure SuperSocket Options
options.Name = "TestServer";
options.ReceiveBufferSize = 2048;
options.SendTimeout = 20000;
options.Listeners = new List<ListenOptions>(){
new ListenOptions{
Ip="Any",
Port = 4042
}
};
})
.UsePackageHandler(async (s, p) =>
{
// Conduct business processing on the received data , And you can choose whether to feed back to the client data
await s.SendAsync(Encoding.UTF8.GetBytes(p + "\r\n"));
})
.Build();
Start Discovery , The length of the filter will be intercepted every time 15 Data packets of , And resolved into StringPackageInfo; When the data length is not enough, it will be placed in the buffer and wait for the next packet to be spliced
(2) Custom filter
The official website said that the built-in filter can meet 90% Scene , But I don't think many types of messages are completely consistent with , In this way, we can learn from the logic of filtering data on the official website , Customize and rewrite your own data filter , The most important filter written by yourself does not have to be a command-line protocol , That is, the terminator does not have to carry \r\n
give an example , Now there is a message that stipulates that the ending character is 0X0A, The total packet length is 17, The data structure is :
It must be such a message structure that we usually contact a lot , Then start writing your own filters now :
/// <summary>
/// Custom data filter
/// </summary>
public class MyFilter : IPipelineFilter<MyPackage>
{
private int _size = 17;
private readonly byte[] _terminator= new byte[] { 0x0A};
public IPackageDecoder<MyPackage> Decoder { get; set; }
public object Context { get; set; }
public IPipelineFilter<MyPackage> NextFilter => null;
public MyPackage Filter(ref SequenceReader<byte> reader)
{
if (reader.Length < _size)
{
// If the length is less than the specified protocol packet length , Not resolved
return null;
}
if (!reader.TryReadTo(out ReadOnlySequence<byte> sequence, _terminator, advancePastDelimiter: false))
{
// If the terminator is not the specified Terminator , Not resolved
return null;
}
ReadOnlySequence<byte> buffer = reader.Sequence.Slice(0, 6);//type
string type = EncodingExtensions.GetString(Encoding.UTF8, buffer).Trim();
ReadOnlySequence<byte> buffer1 = reader.Sequence.Slice(5, 10);
string userName= EncodingExtensions.GetString(Encoding.UTF8, buffer1).Trim();
MyPackage myPackage = new MyPackage { Type=type,UserName=userName };
while (reader.TryRead(out _)) ;
return myPackage;
}
public void Reset() {
}
}
In this custom filter , Inherit IPipelineFilter Interface , Realization Filter Method to control the packet length , Inspection of Terminator , And parse it into a data structure .
Execution results , Return the original data after normal filtering and parsing :
When data is not received properly :
You can see , When data is not received properly , Will filter out and not deal with , And no subsequent business operations .
That's all SuperSocket Simple and basic usage of , The next article introduces Command How to use
版权声明
本文为[Pingshan CP3]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220627116818.html
边栏推荐
- [MySQL] left function | right function
- poi根据数据创建导出excel
- 你真的懂hashCode和equals吗???
- Eight elder brothers chronicle [4]
- 全新的ORM框架——BeetlSQL介绍
- The most easy to understand service container and scope of dependency injection
- Preview of converting doc and PDF to SWF file
- This new feature of C 11, I would like to call it the strongest!
- ThreadLocal test multithreaded variable instance
- The most understandable life cycle of dependency injection
猜你喜欢
Top 9 task management system in 2022
2022年度Top9的任务管理系统
A set of combination boxing to create an idea eye protection scheme
Experiment 6 input / output stream
The most easy to understand service container and scope of dependency injection
Configuration table and page information automatically generate curd operation page
Data mining series (3)_ Data mining plug-in for Excel_ Estimation analysis
ASP. Net 6 middleware series - execution sequence
ASP. Net 6 middleware series - Custom middleware classes
JS inheritance
随机推荐
Generate QR code through zxing
Explanation keyword of MySQL
A comprehensive understanding of static code analysis
可以接收多种数据类型参数——可变参数
Course design of Database Principle -- material distribution management system
Knowledge of software testing~
Eight elder brothers chronicle [4]
软件测试相关知识~
2022山东省安全员C证上岗证题库及在线模拟考试
C语言实现通讯录----(静态版本)
ASP. Net 6 middleware series - execution sequence
IOTOS物联中台对接海康安防平台(iSecure Center)门禁系统
Charles uses three ways to modify requests and responses
ASP. Net and ASP NETCORE multi environment configuration comparison
EasyUI's combobox implements three-level query
[authentication / authorization] customize an authentication handler
General testing technology [1] classification of testing
12. < tag linked list and common test site synthesis > - lt.234 palindrome linked list
场景题:A系统如何使用B系统的页面
The most easy to understand dependency injection and control inversion