当前位置:网站首页>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
边栏推荐
- yes. Net future
- Mise en service PID du moteur de codage (anneau de vitesse | anneau de position | suivant)
- js递归树结构计算每个节点的叶子节点的数量并且输出
- Generate QR code through zxing
- ASP. Net 6 middleware series - execution sequence
- Explication détaillée des fonctions send () et recv () du programme Socket
- Eight elder brothers chronicle [4]
- 场景题:A系统如何使用B系统的页面
- Chapter 8 of C language programming (fifth edition of Tan Haoqiang) is good at using pointer exercises to analyze and answer
- ASP. Net and ASP NETCORE multi environment configuration comparison
猜你喜欢

全新的ORM框架——BeetlSQL介绍

Why is bi so important to enterprises?
![General test technology [II] test method](/img/b7/f661f446616ad6bfbbf48eb03ea82d.png)
General test technology [II] test method

. net tip: talk about the problem that the scoped service cannot be obtained in the middleware structure
![[MySQL] left Function | Right Function](/img/26/82e0f2280de011636c26931a74e749.png)
[MySQL] left Function | Right Function

Experiment 6 input / output stream

xutils3修改了我提报的一个bug,开心

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

软件测试相关知识~
![[MySQL] left function | right function](/img/26/82e0f2280de011636c26931a74e749.png)
[MySQL] left function | right function
随机推荐
[Mysql] LEFT函數 | RIGHT函數
[untitled]
After the mobile phone is connected to the computer, how can QT's QDIR read the mobile phone file path
2022山东省安全员C证上岗证题库及在线模拟考试
js 中,为一个里面带有input 的label 绑定事件后在父元素绑定单机事件,事件执行两次,求解
Xamarin effect Chapter 22 recording effect
Use of metagroup object tuple in C
Flink real-time data warehouse project - Design and implementation of DWS layer
ASP. Net 6 middleware series - Custom middleware classes
Do you really understand hashcode and equals???
MySQL installation pit
ThreadLocal 测试多线程变量实例
TCP three handshakes and four waves
研讨会回放视频:如何提升Jenkins能力,使其成为真正的DevOps平台
MySQL grouping query rules
[MySQL] left Function | Right Function
Explanation keyword of MySQL
Peut recevoir plusieurs paramètres de type de données - paramètres variables
Explication détaillée des fonctions send () et recv () du programme Socket
队列的存储和循环队列