当前位置:网站首页>C# Tcp服务器如何限制同一个IP的连接数量?
C# Tcp服务器如何限制同一个IP的连接数量?
2022-06-27 01:48:00 【若汝棋茗】
一、说明
今天有小伙伴提问,他在使用RRQMSocket创建服务器后,想实现一个功能,就是“限制同一个IP的连接数量”。我和他说,自定义一个插件即可,结果。。。。他不会。
那ok,我给大家示例一下吧。
二、程序集源码
2.1 源码位置
2.2 说明文档
三、安装
Nuget安装RRQMSocket即可,具体步骤详看链接博客。
四、创建插件
class LimitNumberOfConnectionsPlugin : TcpPluginBase
{
[DependencyInject(2)]
public LimitNumberOfConnectionsPlugin(int max,ILog logger)
{
this.Max = max;
this.Logger = logger;
logger.Message($"限制连接插件生效,同一IP限制{
max}个连接");
}
readonly ConcurrentDictionary<string, Count> m_ipToCount = new ConcurrentDictionary<string, Count>();
public int Max {
get; }
protected override void OnConnecting(ITcpClientBase client, ClientOperationEventArgs e)
{
Count count = m_ipToCount.GetOrAdd(client.IP, (s) => {
return new Count(); });
if (count.Increment() > this.Max)
{
count.Decrement();
e.IsPermitOperation = false;//表示不许连接
e.Handled = true;//并且已经处理该消息。
this.Logger.Warning($"IP={
client.IP}的客户端,连接数达到设置阈值。已拒绝连接。");
return;
}
base.OnConnecting(client, e);
}
protected override void OnDisconnected(ITcpClientBase client, ClientDisconnectedEventArgs e)
{
if (m_ipToCount.TryGetValue(client.IP,out Count count))
{
if (count.Decrement() == 0)
{
m_ipToCount.TryRemove(client.IP, out _);
}
}
base.OnDisconnected(client, e);
}
}
class Count
{
private int num;
public int Num
{
get {
return num; }
}
public int Increment()
{
return Interlocked.Increment(ref num);
}
public int Decrement()
{
return Interlocked.Decrement(ref num);
}
}
五、启动服务器
static void Main(string[] args)
{
TcpService service = new TcpService();
service.Connecting += (client, e) => {
};//有客户端正在连接
service.Connected += (client, e) => {
};//有客户端连接
service.Disconnected += (client, e) => {
};//有客户端断开连接
service.Received += (client, byteBlock, requestInfo) =>
{
//从客户端收到信息
string mes = Encoding.UTF8.GetString(byteBlock.Buffer, 0, byteBlock.Len);
Console.WriteLine($"已从{
client.ID}接收到信息:{
mes}");
client.Send(mes);//将收到的信息直接返回给发送方
};
service.Setup(new RRQMConfig()//载入配置
.SetListenIPHosts(new IPHost[] {
new IPHost("127.0.0.1:7789"), new IPHost(7790) })//同时监听两个地址
.SetMaxCount(10000)
.SetThreadCount(100)
.UsePlugin())
.Start();//启动
service.AddPlugin<LimitNumberOfConnectionsPlugin>();
Console.ReadKey();
}
六、效果

因为代码全在这里了,所以,也就不用上传项目了。
边栏推荐
- getReader() has already been called for this request
- Addition, deletion, modification and query of ymal file
- 图论知识及其应用初步调研
- Oracle/PLSQL: Replace Function
- 【系统分析师之路】第六章 复盘需求工程(案例论文)
- memcached基础14
- 速看!2022年6月编程语言排行榜出炉!第一名太牛啦
- Memcached foundation 4
- Some exception handling for idea plug-in development
- Did your case really pass?
猜你喜欢

1.44寸TFT-LCD显示屏取模教程

Browser cache

在连接数据库的时候遇到了点问题,请问怎么解决呀?

SQLite Reader 插件测试SQLite语法

Structure the fifth operation of the actual camp module

George Washington University: Hanhan Zhou | PAC: auxiliary value factor decomposition with counterfactual prediction in Multi-Agent Reinforcement Learning

Continuous delivery blue ocean application

XSS笔记(下)

博日科技招股书失效,中金公司已停止对其辅导,放弃港交所上市?

Due to the invalidation of the prospectus of bori technology, CICC has stopped providing guidance to it and abandoned the listing on the Hong Kong stock exchange?
随机推荐
UVM in UVM_ report_ Enabled usage
hibernate 根据方言生成sql
Why divide the training set and the test set before normalization?
Oracle/PLSQL: Upper Function
Learn the most basic operation of discodiffusion
Memcached foundations 12
Oracle/PLSQL: VSize Function
Oracle/PLSQL: HexToRaw Function
numpy 数组运算机制浅探
Oracle/PLSQL: From_Tz function
Due to the invalidation of the prospectus of bori technology, CICC has stopped providing guidance to it and abandoned the listing on the Hong Kong stock exchange?
Simply learn the entry-level concepts of googlecolab
你的case真的pass了吗?
memcached基礎12
Oracle/PLSQL: NumToDSInterval Function
markdown表格(合并)
Interface test framework practice (I) | requests and interface request construction
Summary of config mechanism and methods in UVM (1)
idea 插件开发一些异常处理
Pointer compression for JVM