C# TCP如何限制单个客户端的访问流量


一、说明

使用TouchSocket创建服务器后,想实现一个限流功能,应该如何实现呢?


二、程序集源码

2.1 源码位置
2.2 说明文档

文档首页

三、安装

Nuget安装TouchSocket即可,具体步骤详看链接博客。

VS、Unity安装和使用Nuget包

四、创建插件

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

实际上,该插件也能用于客户端。同时,也能限制发送流量限制。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

若汝棋茗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值