当前位置:网站首页>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 .
边栏推荐
- [graduation season] role conversion
- C语言--职工信息管理系统设计
- Oracle/PLSQL: NumToDSInterval Function
- Oracle/PLSQL: Translate Function
- memcached基礎12
- NLP: brief introduction of transformer in NLP natural language field (pre training technology), NLP model development (elmo/gpt/bert/mt-dnn/xlnet/roberta/albert), detailed introduction to classic case
- 【系统分析师之路】第六章 复盘需求工程(案例论文)
- Simply learn the entry-level concepts of googlecolab
- Weibo comments on high performance and high availability architecture
- D's appendto packaging
猜你喜欢

SystemVerilog仿真速率提升

WiFi-IoT 鸿蒙开发套件样例开发

dat.gui.js星星圆圈轨迹动画js特效

Daily question brushing record (V)

Why pass SPIF_ Sendchange flag systemparametersinfo will hang?

你的case真的pass了吗?

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?

Ml: a detailed introduction to the division of the top ten roles, backgrounds, responsibilities and outputs of the machine learning engineering team

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

Weibo comments on high performance and high availability architecture
随机推荐
为什么传递SPIF_SENDCHANGE标志SystemParametersInfo会挂起?
Oracle/PLSQL: Lower Function
Oracle/PLSQL: Translate 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?
消费者追捧iPhone,在于它的性价比超越国产手机
每日刷题记录 (五)
Oracle/PLSQL: NumToDSInterval Function
memcached基础9
Oracle/PLSQL: CharToRowid Function
Don't be brainwashed. This is the truth about the wages of 90% of Chinese people
Oracle/PLSQL: To_Clob Function
Learn the most basic operation of discodiffusion
Oracle/PLSQL: Lpad Function
Simply learn the entry-level concepts of googlecolab
接口隔离原则
Why divide the training set and the test set before normalization?
C语言--职工信息管理系统设计
Meituan: data management and pit avoidance strategy summarized after stepping on Thunder for several years
Nokov motion capture system makes it possible for multi field cooperative UAV to build independently
Reporting Classes中uvm_report_server的get_severity_count和get_server用法