一、说明
使用TouchSocket创建服务器后,想实现一个限流功能,应该如何实现呢?
二、程序集源码
2.1 源码位置
2.2 说明文档
三、安装
Nuget安装TouchSocket
即可,具体步骤详看链接博客。
四、创建插件
public class MyThrottlingPlugin : PluginBase, ITcpConnectedPlugin, ITcpReceivingPlugin
{
private readonly int m_max;
[DependencyInject(10)]
public MyThrottlingPlugin(int max)
{
this.m_max = max;
this.Order = int.MaxValue;//提升优先级
}
Task ITcpConnectedPlugin<ITcpClientBase>.OnTcpConnected(ITcpClientBase client, ConnectedEventArgs e)
{
client.InitFlowGate(this.m_max);//初始化流量计数器。
return e.InvokeNext();
}
async Task ITcpReceivingPlugin<ITcpClientBase>.OnTcpReceiving(ITcpClientBase client, ByteBlockEventArgs e)
{
await client.GetFlowGate().AddCheckWaitAsync(e.ByteBlock.Len);
await e.InvokeNext();
}
}
五、创建扩展类
/// <summary>
/// 一个流量计数器扩展。
/// </summary>
internal static class DependencyExtensions
{
public static readonly DependencyProperty<FlowGate> FlowGateProperty =
DependencyProperty<FlowGate>.Register("FlowGate", null);
public static void InitFlowGate(this IDependencyObject dependencyObject, int max)
{
dependencyObject.SetValue(FlowGateProperty, new FlowGate() { Maximum = max });
}
public static FlowGate GetFlowGate(this IDependencyObject dependencyObject)
{
return dependencyObject.GetValue(FlowGateProperty);
}
}
六、启动服务器
/// <summary>
/// 限制单个客户端的访问流量
/// 博客连接<see href="https://blog.csdn.net/qq_40374647/article/details/125496769"/>
/// </summary>
/// <param name="args"></param>
private static void Main(string[] args)
{
var service = new TcpService();
service.Received = (client, byteBlock, requestInfo) =>
{
//从客户端收到信息
var mes = Encoding.UTF8.GetString(byteBlock.Buffer, 0, byteBlock.Len);
client.Logger.Info($"已从{client.Id}接收到信息:{mes}");
};
service.Setup(new TouchSocketConfig()//载入配置
.SetListenIPHosts(new IPHost[] { new IPHost("127.0.0.1:7789"), new IPHost(7790) })//同时监听两个地址
.ConfigureContainer(a =>
{
a.AddConsoleLogger();
})
.ConfigurePlugins(a =>
{
a.Add<MyThrottlingPlugin>();
}))
.Start();//启动
service.Logger.Info("服务器已启动");
Console.ReadLine();
}
七、效果
本文示例demo
实际上,该插件也能用于客户端。同时,也能限制发送流量限制。