You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
3.3 KiB

8 months ago
using DotNetty.Transport.Channels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace HybirdFrameworkServices
{
public class ClientConnectionMonitorHandler : ChannelDuplexHandler
{
//ChannelInboundHandlerAdapter
/// <summary>
/// 监控连接
/// </summary>
/// <param name="ctx"></param>
public override void HandlerAdded(IChannelHandlerContext ctx)
{
Console.WriteLine("Client connected: " + ctx.Channel.RemoteAddress);
string input = ctx.Channel.RemoteAddress.ToString();
// 正则表达式匹配IPv4地址和端口号
string pattern = @"\[(::ffff:)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\]:(\d+)";
Match match = Regex.Match(input, pattern);
// 获取IP地址不包括IPv6前缀
string ipAddress = match.Groups[2].Value;
switch (ipAddress)
{
case "127.0.0.1":
CmnChargingsEqmInfo._ID = ctx.Channel.Id;
CmnChargingsEqmInfo._CHR0IPADDR = ipAddress;
CmnChargingsEqmInfo._CHR0PORT = Convert.ToInt32(match.Groups[3].Value);
CmnChargingsEqmInfo._CHR01.ChargerNetHeartBeatThread();
break;
case "127.0.0.2":
break;
case "127.0.0.3":
break;
case "127.0.0.4":
break;
case "127.0.0.5":
break;
case "127.0.0.6":
break;
case "127.0.0.7":
break;
case "127.0.0.8":
break;
}
}
/// <summary>
/// 监控断开
/// </summary>
/// <param name="ctx"></param>
public override void HandlerRemoved(IChannelHandlerContext ctx)
{
Console.WriteLine("Client disconnected: " + ctx.Channel.RemoteAddress);
string input = ctx.Channel.RemoteAddress.ToString();
// 正则表达式匹配IPv4地址和端口号
string pattern = @"\[(::ffff:)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\]:(\d+)";
Match match = Regex.Match(input, pattern);
// 获取IP地址不包括IPv6前缀
string ipAddress = match.Groups[2].Value;
switch (ipAddress)
{
case "127.0.0.1":
CmnChargingsEqmInfo._CHR01 = null;
break;
case "127.0.0.2":
break;
case "127.0.0.3":
break;
case "127.0.0.4":
break;
case "127.0.0.5":
break;
case "127.0.0.6":
break;
case "127.0.0.7":
break;
case "127.0.0.8":
break;
}
}
public override void ExceptionCaught(IChannelHandlerContext ctx, Exception exception)
{
Console.WriteLine("Exception in ClientConnectionMonitorHandler: " + exception.Message);
}
}
}