当前位置:网站首页>How does the C # TCP server limit the number of connections to the same IP?
How does the C # TCP server limit the number of connections to the same IP?
2022-06-27 01:50:00 【Ruo Qiming】
List of articles
One 、 explain
I have a question today , He's using RRQMSocket After creating the server , Want to achieve a function , Namely “ Limit the same IP Number of connections for ”. I told him , You can customize a plug-in , result .... He won't .
that ok, Let me give you an example .
Two 、 Assembly source code
2.1 Source location
2.2 documentation
The front page of the document
3、 ... and 、 install
Nuget install RRQMSocket that will do , See link blog for specific steps .
VS、Unity Installation and use Nuget package
Four 、 Creating plug-ins
class LimitNumberOfConnectionsPlugin : TcpPluginBase
{
[DependencyInject(2)]
public LimitNumberOfConnectionsPlugin(int max,ILog logger)
{
this.Max = max;
this.Logger = logger;
logger.Message($" Restrict connection plug-ins to take effect , same IP Limit {
max} A connection ");
}
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;// Indicates that connection is not allowed
e.Handled = true;// And the message has been processed .
this.Logger.Warning($"IP={
client.IP} The client of , The number of connections has reached the set threshold . Connection denied .");
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);
}
}
5、 ... and 、 Start the server
static void Main(string[] args)
{
TcpService service = new TcpService();
service.Connecting += (client, e) => {
};// A client is connecting
service.Connected += (client, e) => {
};// There is a client connection
service.Disconnected += (client, e) => {
};// A client is disconnected
service.Received += (client, byteBlock, requestInfo) =>
{
// Receive message from client
string mes = Encoding.UTF8.GetString(byteBlock.Buffer, 0, byteBlock.Len);
Console.WriteLine($" From {
client.ID} Received information :{
mes}");
client.Send(mes);// Return the received information directly to the sender
};
service.Setup(new RRQMConfig()// Load configuration
.SetListenIPHosts(new IPHost[] {
new IPHost("127.0.0.1:7789"), new IPHost(7790) })// Listen to two addresses at the same time
.SetMaxCount(10000)
.SetThreadCount(100)
.UsePlugin())
.Start();// start-up
service.AddPlugin<LimitNumberOfConnectionsPlugin>();
Console.ReadKey();
}
6、 ... and 、 effect

Because the code is all here , therefore , There is no need to upload the project .
边栏推荐
- Memcached basics 14
- Memcached basics 15
- memcached基础14
- 使用命令行安装达梦数据库
- 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?
- memcached基础10
- Hot discussion: what are you doing for a meaningless job with a monthly salary of 18000?
- Online text digit recognition list summation tool
- hibernate 根据方言生成sql
- JVM 的指针压缩
猜你喜欢

I encountered some problems when connecting to the database. How can I solve them?

p5.js死亡星球

为什么传递SPIF_SENDCHANGE标志SystemParametersInfo会挂起?

你的case真的pass了吗?

I earned 3W yuan a month from my sideline: the industry you despise really makes money!

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

Learn the most basic operation of discodiffusion

Interface test framework practice (I) | requests and interface request construction

Continuous delivery blue ocean application

学习DiscoDiffusion的最基础操作
随机推荐
浏览器缓存
“所有专业都在劝退”,对大学生最友好的竟然是它?
Oracle/PLSQL: Rpad Function
Reading a book in idea is too much!
Oracle/PLSQL: NumToYMInterval Function
Oracle/PLSQL: Replace Function
Memcached basics 14
Memcached basics 13
Oracle/PLSQL: Upper Function
lottie.js创意开关按钮动物头像
memcached基础11
Oracle/PLSQL: Cast Function
【系统分析师之路】第六章 复盘需求工程(案例论文)
Oracle/PLSQL: HexToRaw Function
Summary of config mechanism and methods in UVM (1)
Pointer compression for JVM
热议:月薪1.8万却毫无意义的工作,你干吗?
Oracle/PLSQL: Rpad Function
perl语言中 fork()、exec()、waitpid() 、 $? >> 8 组合
BS-GX-016基于SSM实现教材管理系统