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.

100 lines
3.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using BatCharging.Manager;
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 Module.Socket.Tool
{
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);
ctx.Channel.DisconnectAsync();
}
}
}