From 10897922d8ff21d4574a0f7d083f6433cd17950e Mon Sep 17 00:00:00 2001 From: fajiao <1519100073@qq.com> Date: Sat, 6 May 2023 18:34:06 +0800 Subject: [PATCH] =?UTF-8?q?[feat]=20=E8=B0=83=E7=94=A8=20Military=20Api?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- EC.Util/CameraSDK/Common/CameraException.cs | 2 +- EC.Util/CameraSDK/Common/CameraFactory.cs | 16 + EC.Util/CameraSDK/Common/CameraStruct.cs | 59 +- EC.Util/CameraSDK/Common/ICameraSDK.cs | 4 +- EC.Util/CameraSDK/DaHua/DaHuaSDK.cs | 4 +- EC.Util/CameraSDK/HiK/HiKOriSDK.cs | 8 +- EC.Util/CameraSDK/HiK/HiKSDK.cs | 4 +- EC.Util/CameraSDK/YuShi/YuShiSDK.cs | 4 +- EC.Util/Common/DateUnit.cs | 680 ++++++----- EC.Util/Common/FileUnit.cs | 572 +++++---- EC.Util/Common/LogUnit.cs | 29 +- {JiLinApp/Core => EC.Util/Common}/TaskUtil.cs | 9 +- EC.Util/Common/VerifyUtil.cs | 176 +++ EC.Util/Net/APICallBack.cs | 74 +- EC.Util/Net/HttpServer.cs | 606 +++++----- EC.Util/Net/NetUnit.cs | 1036 ++++++++--------- EC.Util/Zmq/ZmqUtil.cs | 2 +- JiLinApp.Biz/TransmitAlarm/Common/Config.cs | 2 + .../TransmitAlarm/Entity/AlarmMessage.cs | 2 +- .../Entity/AlarmMessageHelper.cs | 4 +- .../TransmitAlarm/Service/AlarmMqttService.cs | 61 +- .../TransmitAlarm/Service/AlarmZmqService.cs | 3 + JiLinApp.Docking/Alarm/AlarmCodeHelper.cs | 3 +- .../FenceAlarm/Service/UdpServer.cs | 8 +- JiLinApp.Docking/JiLinApp.Docking.csproj | 4 +- JiLinApp.Docking/Military/Config.cs | 14 + .../Military/Entity/CameraLinkageInfo.cs | 18 + JiLinApp.Docking/Military/MilitaryService.cs | 158 +++ JiLinApp.Docking/Ptz/PtzCmd.cs | 2 +- .../VibrateAlarm/Entity/ClientMessage.cs | 4 +- .../VibrateAlarm/Service/AsyncTcpServer.cs | 93 +- .../VibrateAlarm/Service/TcpManager.cs | 7 +- JiLinApp.sln | 5 + JiLinApp/App.xaml.cs | 3 +- JiLinApp/Components/CameraRealPlay.xaml | 21 +- JiLinApp/Components/CameraRealPlay.xaml.cs | 44 +- JiLinApp/Core/Config.cs | 10 +- JiLinApp/Core/Global.cs | 17 +- JiLinApp/JiLinApp.csproj | 4 +- JiLinApp/Pages/PtzManage/Main.xaml | 3 +- JiLinApp/Pages/PtzManage/Main.xaml.cs | 175 +-- JiLinApp/Pages/PtzManage/MainViewModel.cs | 10 +- JiLinApp/config/config.json | 70 +- 43 files changed, 2235 insertions(+), 1795 deletions(-) create mode 100644 EC.Util/CameraSDK/Common/CameraFactory.cs rename {JiLinApp/Core => EC.Util/Common}/TaskUtil.cs (85%) create mode 100644 EC.Util/Common/VerifyUtil.cs create mode 100644 JiLinApp.Docking/Military/Config.cs create mode 100644 JiLinApp.Docking/Military/Entity/CameraLinkageInfo.cs create mode 100644 JiLinApp.Docking/Military/MilitaryService.cs diff --git a/EC.Util/CameraSDK/Common/CameraException.cs b/EC.Util/CameraSDK/Common/CameraException.cs index c33a62d..a63503c 100644 --- a/EC.Util/CameraSDK/Common/CameraException.cs +++ b/EC.Util/CameraSDK/Common/CameraException.cs @@ -30,7 +30,7 @@ public class CameraException : Exception public override string? ToString() { StringBuilder builder = new(); - builder.Append($"Ip:{CameraInfo?.Ip}, Manufactor:{CameraInfo?.GetManufactor}, Code:{Code}"); + builder.Append($"Ip:{CameraInfo?.Ip}, Manufactor:{CameraInfo?.Manufactor}, Code:{Code}"); if (!string.IsNullOrEmpty(Msg)) builder.Append($", Msg:{Msg}"); return builder.ToString(); } diff --git a/EC.Util/CameraSDK/Common/CameraFactory.cs b/EC.Util/CameraSDK/Common/CameraFactory.cs new file mode 100644 index 0000000..aa9dd3e --- /dev/null +++ b/EC.Util/CameraSDK/Common/CameraFactory.cs @@ -0,0 +1,16 @@ +namespace EC.Util.CameraSDK; + +public class CameraFactory +{ + public static ICameraSDK BuildCameraSdk(CameraInfo info) + { + ICameraSDK sdk = (info.Manufactor) switch + { + CameraManufactor.HiK => new HiKSDK(info), + CameraManufactor.DaHua => new DaHuaSDK(info), + CameraManufactor.YuShi => new YuShiSDK(info), + _ => throw new NotSupportedException(), + }; + return sdk; + } +} \ No newline at end of file diff --git a/EC.Util/CameraSDK/Common/CameraStruct.cs b/EC.Util/CameraSDK/Common/CameraStruct.cs index 42ebda1..547bf3c 100644 --- a/EC.Util/CameraSDK/Common/CameraStruct.cs +++ b/EC.Util/CameraSDK/Common/CameraStruct.cs @@ -5,20 +5,17 @@ /// public class CameraInfo { - #region Attr + #region Fields /// - /// 相机厂商 + /// id /// - public int Manufactor { get; set; } + public string Id { get; set; } = string.Empty; - public CameraManufactor GetManufactor - { - get - { - return (CameraManufactor)Manufactor; - } - } + /// + /// 相机厂商 + /// + public CameraManufactor Manufactor { get; set; } /// /// ip 地址 @@ -40,19 +37,43 @@ public class CameraInfo /// public string Password { get; set; } = string.Empty; - #endregion Attr + #endregion Fields + + public static CameraInfo New(CameraManufactor manufactor, string ip, int port, string username, string password) + { + CameraInfo info = new() { Manufactor = manufactor, Ip = ip, Port = port, UserName = username, Password = password }; + if (port <= 0) throw new Exception("Camera manufactor not support."); + return info; + } + + public static CameraInfo New(CameraManufactor manufactor, string ip, string username, string password) + { + CameraInfo info = new() { Manufactor = manufactor, Ip = ip, UserName = username, Password = password }; + int port = manufactor switch + { + CameraManufactor.HiK => (int)CameraPort.HiK, + CameraManufactor.DaHua => (int)CameraPort.DaHua, + CameraManufactor.YuShi => (int)CameraPort.YuShi, + _ => -1, + }; + if (port <= 0) throw new Exception("Camera manufactor not support."); + info.Port = port; + return info; + } - public static CameraInfo New(int manufactor, string ip, int port, string userName, string password) + public static CameraInfo New(int manufactor, string ip, int port, string username, string password) { - CameraInfo info = new() { Manufactor = manufactor, Ip = ip, Port = port, UserName = userName, Password = password }; + CameraManufactor cm = (CameraManufactor)manufactor; + CameraInfo info = new() { Manufactor = cm, Ip = ip, Port = port, UserName = username, Password = password }; if (port <= 0) throw new Exception("Camera manufactor not support."); return info; } - public static CameraInfo New(int manufactor, string ip, string userName, string password) + public static CameraInfo New(int manufactor, string ip, string username, string password) { - CameraInfo info = new() { Manufactor = manufactor, Ip = ip, UserName = userName, Password = password }; - int port = (CameraManufactor)manufactor switch + CameraManufactor cm = (CameraManufactor)manufactor; + CameraInfo info = new() { Manufactor = cm, Ip = ip, UserName = username, Password = password }; + int port = cm switch { CameraManufactor.HiK => (int)CameraPort.HiK, CameraManufactor.DaHua => (int)CameraPort.DaHua, @@ -90,13 +111,15 @@ public enum CameraPort : int /// public class PtzInfo { - #region Attr + #region Fields public double Pan { get; set; } + public double Tilt { get; set; } + public double Zoom { get; set; } - #endregion Attr + #endregion Fields public PtzInfo(double pan, double tilt, double zoom) { diff --git a/EC.Util/CameraSDK/Common/ICameraSDK.cs b/EC.Util/CameraSDK/Common/ICameraSDK.cs index 60efa38..da4ef00 100644 --- a/EC.Util/CameraSDK/Common/ICameraSDK.cs +++ b/EC.Util/CameraSDK/Common/ICameraSDK.cs @@ -2,11 +2,11 @@ public abstract class ICameraSDK { - #region Attr + #region Fields public CameraInfo CameraInfo { get; } - #endregion Attr + #endregion Fields public ICameraSDK(CameraInfo cameraInfo) { diff --git a/EC.Util/CameraSDK/DaHua/DaHuaSDK.cs b/EC.Util/CameraSDK/DaHua/DaHuaSDK.cs index bcb7cfc..4b940ff 100644 --- a/EC.Util/CameraSDK/DaHua/DaHuaSDK.cs +++ b/EC.Util/CameraSDK/DaHua/DaHuaSDK.cs @@ -4,13 +4,13 @@ namespace EC.Util.CameraSDK; public class DaHuaSDK : ICameraSDK { - #region Attr + #region Fields private IntPtr LoginId { get; set; } = IntPtr.Zero; private IntPtr RealplayHandle { get; set; } = IntPtr.Zero; - #endregion Attr + #endregion Fields public DaHuaSDK(CameraInfo cameraInfo) : base(cameraInfo) { diff --git a/EC.Util/CameraSDK/HiK/HiKOriSDK.cs b/EC.Util/CameraSDK/HiK/HiKOriSDK.cs index 9e02c65..769184a 100644 --- a/EC.Util/CameraSDK/HiK/HiKOriSDK.cs +++ b/EC.Util/CameraSDK/HiK/HiKOriSDK.cs @@ -209,7 +209,7 @@ public static class HiKOriSDK [StructLayout(LayoutKind.Sequential)] public struct NET_DVR_PREVIEWINFO { - public Int32 lChannel; //通道号 + public int lChannel; //通道号 public uint dwStreamType; // 码流类型,0-主码流,1-子码流,2-码流3,3-码流4 等以此类推 public uint dwLinkMode; // 0:TCP方式,1:UDP方式,2:多播方式,3 - RTP方式,4-RTP/RTSP,5-RSTP/HTTP public IntPtr hPlayWnd; //播放窗口的句柄,为NULL表示不播放图象 @@ -304,10 +304,10 @@ public static class HiKOriSDK **********************************************************/ public delegate void REALDATACALLBACK( - Int32 lRealHandle, - UInt32 dwDataType, + int lRealHandle, + uint dwDataType, IntPtr pBuffer, - UInt32 dwBufSize, + uint dwBufSize, IntPtr pUser ); diff --git a/EC.Util/CameraSDK/HiK/HiKSDK.cs b/EC.Util/CameraSDK/HiK/HiKSDK.cs index 320ec28..84629d6 100644 --- a/EC.Util/CameraSDK/HiK/HiKSDK.cs +++ b/EC.Util/CameraSDK/HiK/HiKSDK.cs @@ -4,13 +4,13 @@ namespace EC.Util.CameraSDK; public class HiKSDK : ICameraSDK { - #region Attr + #region Fields private int LoginId { get; set; } = -1; private int RealplayHandle { get; set; } = -1; - #endregion Attr + #endregion Fields public HiKSDK(CameraInfo cameraInfo) : base(cameraInfo) { diff --git a/EC.Util/CameraSDK/YuShi/YuShiSDK.cs b/EC.Util/CameraSDK/YuShi/YuShiSDK.cs index 53c2711..dec8f68 100644 --- a/EC.Util/CameraSDK/YuShi/YuShiSDK.cs +++ b/EC.Util/CameraSDK/YuShi/YuShiSDK.cs @@ -2,13 +2,13 @@ public class YuShiSDK : ICameraSDK { - #region Attr + #region Fields private IntPtr LoginId { get; set; } = IntPtr.Zero; private IntPtr RealplayHandle { get; set; } = IntPtr.Zero; - #endregion Attr + #endregion Fields public YuShiSDK(CameraInfo cameraInfo) : base(cameraInfo) { diff --git a/EC.Util/Common/DateUnit.cs b/EC.Util/Common/DateUnit.cs index f2e6ac8..1bcd732 100644 --- a/EC.Util/Common/DateUnit.cs +++ b/EC.Util/Common/DateUnit.cs @@ -1,439 +1,419 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -/*******************************************************/ +/*******************************************************/ /*Project:基础类库 Module :时间函数库 -Description : +Description : Date : 2008-6-3 15:09:12 Create : Lxc -Update : 2015-12-31 +Update : 2015-12-31 TODO : */ /*******************************************************/ +namespace EC.Util.Common; -namespace System +/// +/// 日期时间操作单元 +/// +public partial class DateUnit { /// - /// 日期时间操作单元 + /// 1970-1-1 /// - public partial class DateUnit + public static DateTime InitDate() { + return new DateTime(1970, 1, 1); + } - /// - /// 1970-1-1 - /// - public static DateTime InitDate() - { - return new DateTime(1970, 1, 1); - } + /// + /// 默认当前日期 + /// + public static DateTime DefDate() + { + return DateTime.Now; + } + + /// + /// 格式化后的当前日期 + /// + public static string DefFormatDate() + { + return FormatDate(DefDate()); + } - /// - /// 默认当前日期 - /// - public static DateTime DefDate() + /// + ///格式化当前时间 + /// + public static string DefFormatDateTime() + { + return FormatDateTime(DefDate()); + } + + /// + /// 格式化后的 当前月1号 日期格式yyyy-MM-01 + /// + public static string DefMonthBegFormat() + { + return DefDate().ToString("yyyy-MM-01"); + } + + /// + /// 字符串格式->格式化为当前日期 + /// + /// + /// + public static string FormatDate(string Indate) + { + DateTime nowDate = DefDate(); + + if (Indate != null && Indate != "") { - return DateTime.Now; + nowDate = ToDate(Indate); } - /// - /// 格式化后的当前日期 - /// - public static string DefFormatDate() + + return FormatDate(nowDate); + } + + /// + /// 格式化为 日期格式yyyy-MM-dd + /// + /// + /// + public static string FormatDate(DateTime Indate) + { + if (!Indate.Equals(null)) { - return FormatDate(DefDate()); + return Indate.ToString("yyyy-MM-dd"); } - /// - ///格式化当前时间 - /// - public static string DefFormatDateTime() + else { - return FormatDateTime(DefDate()); + return DefFormatDate(); } + } - /// - /// 格式化后的 当前月1号 日期格式yyyy-MM-01 - /// - public static string DefMonthBegFormat() + /// + /// 格式化为 日期时间格式yyyy-MM-dd HH:mm:ss + /// + /// + /// + public static string FormatDateTime(DateTime Indate) + { + if (!Indate.Equals(null)) { - return DefDate().ToString("yyyy-MM-01"); + return Indate.ToString("yyyy-MM-dd HH:mm:ss"); } - /// - /// 字符串格式->格式化为当前日期 - /// - /// - /// - public static string FormatDate(string Indate) + else { - DateTime nowDate = DefDate(); - - if (Indate != null && Indate != "") - { - nowDate = ToDate(Indate); - } - - return FormatDate(nowDate); - - + return DefFormatDate(); } - /// - /// 格式化为 日期格式yyyy-MM-dd - /// - /// - /// - public static string FormatDate(DateTime Indate) - { - - if (!Indate.Equals(null)) - { - return Indate.ToString("yyyy-MM-dd"); - } - else - { - return DefFormatDate(); - } + } + /// + /// 格式化时间 毫秒 + /// + /// + /// + public static string FormatDateTimefff(DateTime Indate) + { + if (!Indate.Equals(null)) + { + return Indate.ToString("yyyy-MM-dd HH:mm:ss fff"); } - /// - /// 格式化为 日期时间格式yyyy-MM-dd HH:mm:ss - /// - /// - /// - public static string FormatDateTime(DateTime Indate) + else { + return DefFormatDate(); + } + } - if (!Indate.Equals(null)) - { - return Indate.ToString("yyyy-MM-dd HH:mm:ss"); - } - else - { - return DefFormatDate(); - } + #region 时间函数 + /// + /// 是不是时间格式 + /// + /// + /// + public static bool IsDate(string datetm) + { + bool result = false; + try + { + DateTime dateTime = Convert.ToDateTime(datetm); + result = true; } - /// - /// 格式化时间 毫秒 - /// - /// - /// - public static string FormatDateTimefff(DateTime Indate) + catch { + result = false; + } + return result; + } - if (!Indate.Equals(null)) - { - return Indate.ToString("yyyy-MM-dd HH:mm:ss fff"); - } + /// + /// 将字符串转化成日期,如果输入的字符串不是日期时,则返回1970-1-1 + /// + /// + /// + public static DateTime ToDate(string str) + { + if (str == null || str == "") + return DefDate(); + else + { + DateTime dt = DefDate(); + if (DateTime.TryParse(str, out dt) == false) + return DefDate(); else - { - return DefFormatDate(); - } - + return dt; } + } - - #region 时间函数 - - /// - /// 是不是时间格式 - /// - /// - /// - public static bool IsDate(string datetm) + /// + /// 将对象转化成日期,如果输入的对象不是日期时,则返回1970-1-1 + /// + /// + /// + public static DateTime ToDate(object obj) + { + DateTime Result = DefDate(); + if (!obj.Equals(null)) { - bool result = false; try { - DateTime dateTime = Convert.ToDateTime(datetm); - result = true; + Result = (DateTime)obj; } - catch + catch (Exception ex) { - result = false; - + return DefDate(); } - return result; + //if (DateTime.TryParse(obj.ToString(), out Result) == false) + // return DefDate; } + return Result; + } - - /// - /// 将字符串转化成日期,如果输入的字符串不是日期时,则返回1970-1-1 - /// - /// - /// - public static DateTime ToDate(string str) + /// + /// 将对象转化成日期,如果输入的对象不是日期时,则返回1900-1-1 + /// + /// + /// + public static DateTime ToDate(System.Nullable obj) + { + if (!obj.Equals(null)) { - if (str == null || str == "") - return DefDate(); - else - { - DateTime dt = DefDate(); - if (DateTime.TryParse(str, out dt) == false) - return DefDate(); - else - return dt; - } + return (DateTime)obj; } - - /// - /// 将对象转化成日期,如果输入的对象不是日期时,则返回1970-1-1 - /// - /// - /// - public static DateTime ToDate(object obj) + else { - DateTime Result = DefDate(); - if (!obj.Equals(null)) - { - try - { - Result = (DateTime)obj; - } - catch (Exception ex) - { - return DefDate(); - } - //if (DateTime.TryParse(obj.ToString(), out Result) == false) - // return DefDate; - } - return Result; + return DefDate(); } + } - /// - /// 将对象转化成日期,如果输入的对象不是日期时,则返回1900-1-1 - /// - /// - /// - public static DateTime ToDate(System.Nullable obj) + /// + /// 20070101-->2007-01-01 + /// + /// + /// + public static string StrTodate(string Str) + { + string stryear, strmon, strday; + try { - if (!obj.Equals(null)) - { - - return (DateTime)obj; - } - else - { - return DefDate(); - } - + stryear = Str.Remove(4, 4); + Str = Str.Remove(0, 4); + strmon = Str.Remove(2, 2); + strday = Str.Remove(0, 2); + stryear = stryear + "-" + strmon + "-" + strday; + return stryear; } - - - /// - /// 20070101-->2007-01-01 - /// - /// - /// - public static string StrTodate(string Str) + catch { - string stryear, strmon, strday; - try - { - stryear = Str.Remove(4, 4); - Str = Str.Remove(0, 4); - strmon = Str.Remove(2, 2); - strday = Str.Remove(0, 2); - stryear = stryear + "-" + strmon + "-" + strday; - return stryear; - } - catch - { - return DefFormatDate(); - } - + return DefFormatDate(); } + } + #endregion 时间函数 + #region 周计算 - #endregion - - #region 周计算 - - /// - /// 周几 - /// - /// - /// - public static string DayOfWeek(DateTime curDay) - { + /// + /// 周几 + /// + /// + /// + public static string DayOfWeek(DateTime curDay) + { + string[] weekdays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; + string week = weekdays[Convert.ToInt32(curDay.DayOfWeek)]; + return week; + } - string[] weekdays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; - string week = weekdays[Convert.ToInt32(curDay.DayOfWeek)]; + /// + /// 第几周 + /// + /// + /// + public static int WeekOfYear(DateTime curDay) + { + int firstdayofweek = Convert.ToInt32(Convert.ToDateTime(curDay.Year.ToString() + "-" + "1-1").DayOfWeek); - return week; + int days = curDay.DayOfYear; + int daysOutOneWeek = days - (7 - firstdayofweek); + if (daysOutOneWeek <= 0) + { + return 1; } - - /// - /// 第几周 - /// - /// - /// - public static int WeekOfYear(DateTime curDay) + else { + int weeks = daysOutOneWeek / 7; + if (daysOutOneWeek % 7 != 0) + weeks++; - int firstdayofweek = Convert.ToInt32(Convert.ToDateTime(curDay.Year.ToString() + "-" + "1-1").DayOfWeek); - - int days = curDay.DayOfYear; - int daysOutOneWeek = days - (7 - firstdayofweek); - - if (daysOutOneWeek <= 0) - { - return 1; - } - else - { - int weeks = daysOutOneWeek / 7; - if (daysOutOneWeek % 7 != 0) - weeks++; - - return weeks + 1; - } + return weeks + 1; } + } - #region 返回某年某月最后一天 - /// - /// 返回某年某月最后一天 - /// - /// 年份 - /// 月份 - /// - public static int GetMonthLastDate(int year, int month) - { - DateTime lastDay = new DateTime(year, month, new System.Globalization.GregorianCalendar().GetDaysInMonth(year, month)); - int Day = lastDay.Day; - return Day; - } - #endregion + #region 返回某年某月最后一天 + /// + /// 返回某年某月最后一天 + /// + /// 年份 + /// 月份 + /// + public static int GetMonthLastDate(int year, int month) + { + DateTime lastDay = new DateTime(year, month, new System.Globalization.GregorianCalendar().GetDaysInMonth(year, month)); + int Day = lastDay.Day; + return Day; + } - #endregion + #endregion 返回某年某月最后一天 + #endregion 周计算 - #region 返回时间差 - /// - /// 返回时间差 秒 - /// - /// - /// - /// - public static double DateDiffSeconds(DateTime begDateTime, DateTime endDateTime) - { + #region 返回时间差 - try - { - TimeSpan ts = endDateTime - begDateTime; - return ts.TotalSeconds; - } - catch (Exception) - { - return 0; - } - } - /// - /// 返回时间差 分钟 - /// - /// - /// - /// - public static double DateDiffMinutes(DateTime begDateTime, DateTime endDateTime) + /// + /// 返回时间差 秒 + /// + /// + /// + /// + public static double DateDiffSeconds(DateTime begDateTime, DateTime endDateTime) + { + try { - - try - { - TimeSpan ts = endDateTime - begDateTime; - return ts.TotalMinutes; - } - catch (Exception) - { - return 0; - } + TimeSpan ts = endDateTime - begDateTime; + return ts.TotalSeconds; } - public static double DateDiffHours(DateTime begDateTime, DateTime endDateTime) + catch (Exception) { - - try - { - TimeSpan ts = endDateTime - begDateTime; - return ts.TotalHours; - } - catch (Exception) - { - return 0; - } + return 0; } - public static double DateDifDays(DateTime begDateTime, DateTime endDateTime) - { + } - try - { - TimeSpan ts = endDateTime - begDateTime; - return ts.TotalDays; - } - catch (Exception) - { - return 0; - } + /// + /// 返回时间差 分钟 + /// + /// + /// + /// + public static double DateDiffMinutes(DateTime begDateTime, DateTime endDateTime) + { + try + { + TimeSpan ts = endDateTime - begDateTime; + return ts.TotalMinutes; } - #endregion - - /// - /// Unix时间戳 - /// - /// 毫秒 - public static long UnixTime() + catch (Exception) { - System.DateTime time = DateTime.Now; - System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)); - long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位 - return t; + return 0; } - /// - /// 将c# DateTime时间格式转换为Unix时间戳格式 - /// - /// 时间 - /// 毫秒 - public static long DateTimeToUnixTime(System.DateTime time) + } + + public static double DateDiffHours(DateTime begDateTime, DateTime endDateTime) + { + try { - System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)); - long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位 - return t; + TimeSpan ts = endDateTime - begDateTime; + return ts.TotalHours; } - /// - /// 时间戳转为C#格式时间 - /// - /// - /// - public static DateTime UnixTimeToDateTime(long timeStamp) + catch (Exception) { - DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); - long lTime = timeStamp * 10000; - TimeSpan toNow = new TimeSpan(lTime); - return dtStart.Add(toNow); + return 0; } + } - /// - /// Unix时间戳 时间格式化 为日期 - /// - /// - /// - public static string FormatDateUnixTime(long timeStamp) + public static double DateDifDays(DateTime begDateTime, DateTime endDateTime) + { + try { - DateTime dtStart = UnixTimeToDateTime(timeStamp); - return FormatDate(dtStart); + TimeSpan ts = endDateTime - begDateTime; + return ts.TotalDays; } - /// - /// Unix时间戳 时间格式化 为时间 - /// - /// - /// - public static string FormatDateTimeUnixTime(long timeStamp) + catch (Exception) { - DateTime dtStart = UnixTimeToDateTime(timeStamp); - return FormatDateTime(dtStart); + return 0; } + } + + #endregion 返回时间差 + + /// + /// Unix时间戳 + /// + /// 毫秒 + public static long UnixTime() + { + System.DateTime time = DateTime.Now; + System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)); + long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位 + return t; + } + + /// + /// 将c# DateTime时间格式转换为Unix时间戳格式 + /// + /// 时间 + /// 毫秒 + public static long DateTimeToUnixTime(System.DateTime time) + { + System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)); + long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位 + return t; + } + /// + /// 时间戳转为C#格式时间 + /// + /// + /// + public static DateTime UnixTimeToDateTime(long timeStamp) + { + DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); + long lTime = timeStamp * 10000; + TimeSpan toNow = new TimeSpan(lTime); + return dtStart.Add(toNow); + } + + /// + /// Unix时间戳 时间格式化 为日期 + /// + /// + /// + public static string FormatDateUnixTime(long timeStamp) + { + DateTime dtStart = UnixTimeToDateTime(timeStamp); + return FormatDate(dtStart); + } + + /// + /// Unix时间戳 时间格式化 为时间 + /// + /// + /// + public static string FormatDateTimeUnixTime(long timeStamp) + { + DateTime dtStart = UnixTimeToDateTime(timeStamp); + return FormatDateTime(dtStart); } -} +} \ No newline at end of file diff --git a/EC.Util/Common/FileUnit.cs b/EC.Util/Common/FileUnit.cs index c32b9d9..ec92367 100644 --- a/EC.Util/Common/FileUnit.cs +++ b/EC.Util/Common/FileUnit.cs @@ -1,367 +1,359 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.IO; -using System.Web; -/*******************************************************/ +/*******************************************************/ /*Project:基础类库 Module :文件操作库 Description : 文本读写,日志 Date : 2008-6-3 15:09:12 Create : Lxc -Update : 2014-12-31 +Update : 2014-12-31 TODO : */ /*******************************************************/ -namespace System -{ + +namespace EC.Util.Common; + +/// +/// 文件操作单元 +/// +public partial class FileUnit +{ + private static readonly string AppFilepatch = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; + /// - /// 文件操作单元 + /// 创建目录 /// - public partial class FileUnit + /// + /// + public static bool CreateDir(string fullPath) { - static readonly string AppFilepatch = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase; - /// - /// 创建目录 - /// - /// - /// - public static bool CreateDir(string fullPath) + if (!Directory.Exists(fullPath)) { - if (!Directory.Exists(fullPath)) + try { - try - { - Directory.CreateDirectory(fullPath); - return true; - } - catch (Exception ex) - { - return false; - } + Directory.CreateDirectory(fullPath); + return true; + } + catch (Exception ex) + { + return false; } - return true; - } - //删除文件名 获取路径 - public static string GetDirectory(string fullPath) - { - return Path.GetDirectoryName(fullPath); - //return allFileName.Substring(0, allFileName.LastIndexOf('\\')); - } - /// - /// 得到文件名称 - /// - /// - /// - public static string GetFileName(string fullPath) - { - return Path.GetFileName(fullPath); - } - /// - /// 得到扩展名 - /// - /// - /// - public static string GetFileExt(string fullPath) - { - return Path.GetExtension(fullPath); - } - /// - /// 得到名称没有扩展名 - /// - /// - /// - public static string GetFileNameNoExt(string fullPath) - { - return Path.GetFileNameWithoutExtension(fullPath); } - /// - /// 复制文件 - /// - /// - /// - /// - public static string CopyFile(string sourceFileName, string destFileName) + return true; + } + + //删除文件名 获取路径 + public static string GetDirectory(string fullPath) + { + return Path.GetDirectoryName(fullPath); + //return allFileName.Substring(0, allFileName.LastIndexOf('\\')); + } + + /// + /// 得到文件名称 + /// + /// + /// + public static string GetFileName(string fullPath) + { + return Path.GetFileName(fullPath); + } + + /// + /// 得到扩展名 + /// + /// + /// + public static string GetFileExt(string fullPath) + { + return Path.GetExtension(fullPath); + } + + /// + /// 得到名称没有扩展名 + /// + /// + /// + public static string GetFileNameNoExt(string fullPath) + { + return Path.GetFileNameWithoutExtension(fullPath); + } + + /// + /// 复制文件 + /// + /// + /// + /// + public static string CopyFile(string sourceFileName, string destFileName) + { + try { - try + if (File.Exists(sourceFileName)) { - if (File.Exists(sourceFileName)) + string destDirectory = GetDirectory(destFileName);// destFileName.Substring(0, destFileName.LastIndexOf('\\'));//删除文件名 获取路径 + bool createDir = CreateDir(destDirectory); + if (createDir) { - string destDirectory = GetDirectory(destFileName);// destFileName.Substring(0, destFileName.LastIndexOf('\\'));//删除文件名 获取路径 - bool createDir = CreateDir(destDirectory); - if (createDir) - { - File.Copy(sourceFileName, destFileName); - } - else - { - return "文件路径" + destFileName + "不正确!"; - } + File.Copy(sourceFileName, destFileName); } else { - return "文件路径" + sourceFileName + "不存在!"; + return "文件路径" + destFileName + "不正确!"; } - return ""; } - catch (Exception ex) + else { - return ex.Message; + return "文件路径" + sourceFileName + "不存在!"; } - - + return ""; } - /// - /// 得到路径 没有扩展名 - /// - /// - /// - public static string GetPathNoExt(string rptPath) + catch (Exception ex) { - string rtpDir = GetDirectory(rptPath); - string disFileName = GetFileNameNoExt(rptPath); - string disPatch = rtpDir + "\\" + disFileName;// +".docx"; - return disPatch; + return ex.Message; } - /// - /// 读取文本 - /// - /// - /// - public static string ReadtxtFile(string filename) + } + + /// + /// 得到路径 没有扩展名 + /// + /// + /// + public static string GetPathNoExt(string rptPath) + { + string rtpDir = GetDirectory(rptPath); + string disFileName = GetFileNameNoExt(rptPath); + string disPatch = rtpDir + "\\" + disFileName;// +".docx"; + return disPatch; + } + + /// + /// 读取文本 + /// + /// + /// + public static string ReadtxtFile(string filename) + { + try { - - try + if (File.Exists(filename)) { - if (File.Exists(filename)) + // Create an instance of StreamReader to read from a file. + // The using statement also closes the StreamReader. + using (StreamReader sr = new StreamReader(filename, System.Text.Encoding.UTF8)) { - // Create an instance of StreamReader to read from a file. - // The using statement also closes the StreamReader. - using (StreamReader sr = new StreamReader(filename, System.Text.Encoding.UTF8)) - { - return sr.ReadToEnd(); - } + return sr.ReadToEnd(); } - else LogUnit.Error(typeof(FileUnit),"no exists " + filename); - } - catch (Exception e) - { - LogUnit.Error(typeof(FileUnit), e.ToString()); - } - return ""; - + else LogUnit.Error(typeof(FileUnit), "no exists " + filename); } + catch (Exception e) + { + LogUnit.Error(typeof(FileUnit), e.ToString()); + } + return ""; + } - /// - /// 读取多行文本 - /// - /// - /// - public static List ReadtxtLinesFile(string filename) + /// + /// 读取多行文本 + /// + /// + /// + public static List ReadtxtLinesFile(string filename) + { + List filtxtLines = new List(); + try { - List filtxtLines = new List(); - try + if (File.Exists(filename)) { - if (File.Exists(filename)) + // Create an instance of StreamReader to read from a file. + // The using statement also closes the StreamReader. + using (StreamReader sr = new StreamReader(filename, System.Text.Encoding.UTF8)) { - // Create an instance of StreamReader to read from a file. - // The using statement also closes the StreamReader. - using (StreamReader sr = new StreamReader(filename, System.Text.Encoding.UTF8)) + String line; + // Read and display lines from the file until the end of + // the file is reached. + while ((line = sr.ReadLine()) != null) { - String line; - // Read and display lines from the file until the end of - // the file is reached. - while ((line = sr.ReadLine()) != null) - { - filtxtLines.Add(line); - } + filtxtLines.Add(line); } } } - catch (Exception e) - { - LogUnit.Error(typeof(FileUnit), e.ToString()); - } - return filtxtLines; } + catch (Exception e) + { + LogUnit.Error(typeof(FileUnit), e.ToString()); + } + return filtxtLines; + } - /// - /// 读取多行文本 - /// - /// - /// - /// - /// - public static bool WritetxtFileLine(string filepatch,string filename, List txtLines) + /// + /// 读取多行文本 + /// + /// + /// + /// + /// + public static bool WritetxtFileLine(string filepatch, string filename, List txtLines) + { + List filtxtLines = new List(); + try { - - List filtxtLines = new List(); - try + if (!Directory.Exists(filepatch)) { - - - if (!Directory.Exists(filepatch)) - { - Directory.CreateDirectory(filepatch); - } - using (StreamWriter sw = new StreamWriter(filepatch + filename, false, System.Text.Encoding.UTF8)) - { - foreach (string str in txtLines) - { - sw.WriteLine(str); - } - sw.Close(); - } - + Directory.CreateDirectory(filepatch); } - catch (Exception e) + using (StreamWriter sw = new StreamWriter(filepatch + filename, false, System.Text.Encoding.UTF8)) { - LogUnit.Error(typeof(FileUnit), e.ToString()); - return false; + foreach (string str in txtLines) + { + sw.WriteLine(str); + } + sw.Close(); } - return true; } - /// - /// 写入文本 - /// - /// - /// - /// - /// - public static bool WritetxtFile(string filepatch, string filename, string text) + catch (Exception e) { + LogUnit.Error(typeof(FileUnit), e.ToString()); + return false; + } + return true; + } - List filtxtLines = new List(); - try + /// + /// 写入文本 + /// + /// + /// + /// + /// + public static bool WritetxtFile(string filepatch, string filename, string text) + { + List filtxtLines = new List(); + try + { + if (!Directory.Exists(filepatch)) { - - if (!Directory.Exists(filepatch)) - { - Directory.CreateDirectory(filepatch); - } - - using (StreamWriter sw = new StreamWriter(filepatch + filename, false, System.Text.Encoding.UTF8)) - { - - sw.Write(text); - - sw.Close(); - } - + Directory.CreateDirectory(filepatch); } - catch (Exception e) + + using (StreamWriter sw = new StreamWriter(filepatch + filename, false, System.Text.Encoding.UTF8)) { - LogUnit.Error(typeof(FileUnit), e.ToString()); - return false; + sw.Write(text); + + sw.Close(); } - return true; } - - private static bool Log(string subfilepatch,string logmessage) + catch (Exception e) { + LogUnit.Error(typeof(FileUnit), e.ToString()); + return false; + } + return true; + } - try + private static bool Log(string subfilepatch, string logmessage) + { + try + { + string logfilePath = AppFilepatch + "Log\\" + subfilepatch; + if (!Directory.Exists(logfilePath)) { - string logfilePath = AppFilepatch + "Log\\" + subfilepatch ; - if (!Directory.Exists(logfilePath)) - { - Directory.CreateDirectory(logfilePath); - } - using (StreamWriter sw = new StreamWriter(logfilePath + DateTime.Now.ToString("yyyyMMdd") + ".txt", true, System.Text.Encoding.UTF8)) - { - sw.WriteLine(DateTime.Now.ToString() + " : " + logmessage); - sw.Close(); - } + Directory.CreateDirectory(logfilePath); } - catch (Exception e) + using (StreamWriter sw = new StreamWriter(logfilePath + DateTime.Now.ToString("yyyyMMdd") + ".txt", true, System.Text.Encoding.UTF8)) { - return false; + sw.WriteLine(DateTime.Now.ToString() + " : " + logmessage); + sw.Close(); } - return true; } - - //支付日志 - public static void PayLog(string log) + catch (Exception e) { - string path = "PayLog\\"; - Log(path, log); + return false; } + return true; + } - //订单日志 - public static void OrderLog(string log) - { - string path = "OrderLog\\"; - Log(path, log); - } + //支付日志 + public static void PayLog(string log) + { + string path = "PayLog\\"; + Log(path, log); + } - //写入日志 - public static void Log(string log) - { - string path = ""; - Log(path, log); - } - public static void WebLog(string log) - { - Log(log); - } - - //public static void WebLog(string log) - //{ - // string path = HttpContext.Current.Server.MapPath(".")+"Web\\"; - // Log(path, log); - //} + //订单日志 + public static void OrderLog(string log) + { + string path = "OrderLog\\"; + Log(path, log); + } - public static void ErrLog(string log) - { - string subpath = "ErrLog\\"; - Log(subpath, log); - } - public static void HisLog(string log) - { - string subpath = "HisLog\\"; - Log(subpath, log); - } + //写入日志 + public static void Log(string log) + { + string path = ""; + Log(path, log); + } - - public static void Package(string log) - { - string path = "Package\\"; - Log(path, log); - } + public static void WebLog(string log) + { + Log(log); + } - - public static void EPS(string log) - { - string path = "EPS\\"; - Log(path, log); - } - public static void AllLog(string log) - { - string path = "AllLog\\"; - Log(path, log); - } - public static bool Exists(string path) - { - return File.Exists(path); - } - public static void DeleteFile(string path) + //public static void WebLog(string log) + //{ + // string path = HttpContext.Current.Server.MapPath(".")+"Web\\"; + // Log(path, log); + //} + + public static void ErrLog(string log) + { + string subpath = "ErrLog\\"; + Log(subpath, log); + } + + public static void HisLog(string log) + { + string subpath = "HisLog\\"; + Log(subpath, log); + } + + public static void Package(string log) + { + string path = "Package\\"; + Log(path, log); + } + + public static void EPS(string log) + { + string path = "EPS\\"; + Log(path, log); + } + + public static void AllLog(string log) + { + string path = "AllLog\\"; + Log(path, log); + } + + public static bool Exists(string path) + { + return File.Exists(path); + } + + public static void DeleteFile(string path) + { + try { - try + if (File.Exists(path)) { - if (File.Exists(path)) - { - File.Delete(path); - } - else - { - LogUnit.Error(typeof(FileUnit), "路径不存在" + path); - } + File.Delete(path); } - catch (Exception ex) + else { - LogUnit.Error(typeof(FileUnit), ex.ToString()); + LogUnit.Error(typeof(FileUnit), "路径不存在" + path); } } + catch (Exception ex) + { + LogUnit.Error(typeof(FileUnit), ex.ToString()); + } } -} +} \ No newline at end of file diff --git a/EC.Util/Common/LogUnit.cs b/EC.Util/Common/LogUnit.cs index 5995fd7..fd16cd0 100644 --- a/EC.Util/Common/LogUnit.cs +++ b/EC.Util/Common/LogUnit.cs @@ -1,9 +1,7 @@ using log4net; using log4net.Config; -using System; -using System.IO; -namespace System; +namespace EC.Util.Common; public static class LogUnit { @@ -49,19 +47,24 @@ public static class LogUnit { logger.Error(e); } - /// - /// 输出日志到Log4Net - /// - /// - /// - public static void Error(Type t, Exception ex) + + public static void Error(object obj, Exception e) { - - logger.Error("Error", ex); + logger.Error(obj.GetType(), e); } - public static void Error(Type t, string logMessage) + + public static void Error(object obj, string msg) { + logger.Error(obj.GetType(), new Exception(msg)); + } - logger.Error(logMessage); + public static void Error(Type type, Exception e) + { + logger.Error(type, e); + } + + public static void Error(Type type, string msg) + { + logger.Error(type, new Exception(msg)); } } \ No newline at end of file diff --git a/JiLinApp/Core/TaskUtil.cs b/EC.Util/Common/TaskUtil.cs similarity index 85% rename from JiLinApp/Core/TaskUtil.cs rename to EC.Util/Common/TaskUtil.cs index f9fa738..a691590 100644 --- a/JiLinApp/Core/TaskUtil.cs +++ b/EC.Util/Common/TaskUtil.cs @@ -1,9 +1,6 @@ -using System; -using System.Threading.Tasks; +namespace EC.Util.Common; -namespace JiLinApp.Core; - -public static class TaskUtil +public class TaskUtil { public static Task Run(Action action) { @@ -25,7 +22,7 @@ public static class TaskUtil } catch (Exception e) { - LogUnit.Error(e); + LogUnit.Error(typeof(TaskUtil), e); } }); } diff --git a/EC.Util/Common/VerifyUtil.cs b/EC.Util/Common/VerifyUtil.cs new file mode 100644 index 0000000..d575597 --- /dev/null +++ b/EC.Util/Common/VerifyUtil.cs @@ -0,0 +1,176 @@ +using System.Text.RegularExpressions; + +namespace EC.Util.Common; + +/// +/// 验证工具类 +/// +public class VerifyUtil +{ + /// + /// 验证是否为空 + /// + /// + /// + public static bool IsEmpty(string str) + { + return string.IsNullOrEmpty(str); + } + + /// + /// 验证是否为邮件 + /// + /// + /// + public static bool IsEmail(string emailStr) + { + if (string.IsNullOrEmpty(emailStr)) return false; + string match = @"^([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$"; + Regex r = new(match, RegexOptions.Compiled | RegexOptions.IgnoreCase); + return r.IsMatch(emailStr.Trim()); + } + + /// + /// 验证是否为数字 + /// + /// + /// + public static bool IsNumber(string numberStr) + { + if (string.IsNullOrEmpty(numberStr)) return false; + string match = @"^(0|[1-9][0-9]*)$"; + Regex r = new(match, RegexOptions.Compiled | RegexOptions.IgnoreCase); + return r.IsMatch(numberStr.Trim()); + } + + /// + /// 验证是否为浮点数 + /// + /// + /// + public static bool IsDecimal(string decimalStr) + { + if (string.IsNullOrEmpty(decimalStr)) return false; + string match = @"^(-?\d+)(\.\d+)?$"; + Regex r = new(match, RegexOptions.Compiled | RegexOptions.IgnoreCase); + return r.IsMatch(decimalStr.Trim()); + } + + /// + /// 验证是否为手机号码 + /// + /// + /// + public static bool IsMobile(string mobileStr) + { + if (string.IsNullOrEmpty(mobileStr)) return false; + string match = @"^[1]+[3,5,7,8]+\d{9}"; + Regex r = new(match, RegexOptions.Compiled | RegexOptions.IgnoreCase); + return r.IsMatch(mobileStr.Trim()); + } + + /// + /// 验证是否为电话号码 + /// + /// + /// + public static bool IsTel(string telStr) + { + if (string.IsNullOrEmpty(telStr)) return false; + string match = @"^(\+86\s{1,1})?((\d{3,4}\-)\d{7,8})$"; + Regex r = new(match, RegexOptions.Compiled | RegexOptions.IgnoreCase); + return r.IsMatch(telStr.Trim()); + } + + /// + /// 验证是否为Ip地址 + /// + /// + /// + public static bool IsIp(string ipStr) + { + if (string.IsNullOrEmpty(ipStr)) return false; + string match = @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$"; + Regex r = new(match); + return r.IsMatch(ipStr.Trim()); + } + + /// + /// 验证是否为身份证 + /// + /// 身份证号 + /// + public static bool CheckIDCard(string idcardStr) + { + if (string.IsNullOrEmpty(idcardStr)) return false; + if (idcardStr.Length == 18) return CheckIDCard18(idcardStr); + else if (idcardStr.Length == 15) return CheckIDCard15(idcardStr); + return false; + } + + /// + /// 18位身份证验证 + /// + /// 身份证号 + /// + private static bool CheckIDCard18(string Id) + { + long n = 0; + if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false) + { + return false;//数字验证 + } + string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91"; + if (address.IndexOf(Id.Remove(2)) == -1) + { + return false;//省份验证 + } + string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-"); + DateTime time = new DateTime(); + if (DateTime.TryParse(birth, out time) == false) + { + return false;//生日验证 + } + string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(','); + string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(','); + char[] Ai = Id.Remove(17).ToCharArray(); + int sum = 0; + for (int i = 0; i < 17; i++) + { + sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString()); + } + int y = -1; + Math.DivRem(sum, 11, out y); + if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower()) + { + return false;//校验码验证 + } + return true;//符合GB11643-1999标准 + } + + /// + /// 15位身份证验证 + /// + /// 身份证号 + /// + private static bool CheckIDCard15(string Id) + { + long n = 0; + if (long.TryParse(Id, out n) == false || n < Math.Pow(10, 14)) + { + return false;//数字验证 + } + string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91"; + if (address.IndexOf(Id.Remove(2)) == -1) + { + return false;//省份验证 + } + string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-"); + DateTime time = new DateTime(); + if (DateTime.TryParse(birth, out time) == false) + { + return false;//生日验证 + } + return true;//符合15位身份证标准 + } +} \ No newline at end of file diff --git a/EC.Util/Net/APICallBack.cs b/EC.Util/Net/APICallBack.cs index ea48d39..31c8001 100644 --- a/EC.Util/Net/APICallBack.cs +++ b/EC.Util/Net/APICallBack.cs @@ -1,39 +1,39 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace EC.Util.Net; -namespace EC.Util.Net +public class APICallBack { - public class APICallBack - { - public string reqCode { get; set; } - /// - /// 任务单号 - /// - public string taskCode { get; set; } - /// - /// AGV状态指令 - /// - public string method { get; set; } - public string reqTime { get; set; } - public string wbCode { get; set; } - /// - /// AGV编号 - /// - public string robotCode { get; set; } - /// - /// 请求AGV接口后返回的成功失败或其他消息 - /// - public string message { get; set; } - /// - /// 请求AGV接口后返回的任务单号 - /// - public string data { get; set; } - /// - /// 请求AGV接口后返回的任务状态 - /// - public string code { get; set; } - } -} + public string reqCode { get; set; } + + /// + /// 任务单号 + /// + public string taskCode { get; set; } + + /// + /// AGV状态指令 + /// + public string method { get; set; } + + public string reqTime { get; set; } + public string wbCode { get; set; } + + /// + /// AGV编号 + /// + public string robotCode { get; set; } + + /// + /// 请求AGV接口后返回的成功失败或其他消息 + /// + public string message { get; set; } + + /// + /// 请求AGV接口后返回的任务单号 + /// + public string data { get; set; } + + /// + /// 请求AGV接口后返回的任务状态 + /// + public string code { get; set; } +} \ No newline at end of file diff --git a/EC.Util/Net/HttpServer.cs b/EC.Util/Net/HttpServer.cs index 8cc5a28..ce7c297 100644 --- a/EC.Util/Net/HttpServer.cs +++ b/EC.Util/Net/HttpServer.cs @@ -1,362 +1,358 @@ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; +using EC.Util.Common; using System.Net; using System.Text; -using System.Threading; -using System.Threading.Tasks; -namespace EC.Util.Net +namespace EC.Util.Net; + +public class HttpServer { - public class HttpServer + public event EventHandler OnRecData; //定义一个委托类型的事件 + + #region + + public string Host { get; set; } + public string port { get; set; } + private string _webHomeDir = ""; + private HttpListener listener; + private Thread listenThread; + private string directorySeparatorChar = Path.DirectorySeparatorChar.ToString(); + public string ImageUploadPath { get; set; } + + /// + /// 设置监听端口,重启服务生效 + /// + //public string Port + //{ + // get { return this.port; } + // set + // { + // int p; + // if (string.IsNullOrEmpty(value) || !int.TryParse(value, out p)) + // { + // throw new Exception("给http监听器赋值的端口号无效!"); + // } + // this.port = value; + // } + //} + /// + /// http服务根目录 + /// + public string WebHomeDir { - - public event EventHandler OnRecData; //定义一个委托类型的事件 - #region - - public string Host { get; set; } - public string port { get; set; } - private string _webHomeDir = ""; - private HttpListener listener; - private Thread listenThread; - private string directorySeparatorChar = Path.DirectorySeparatorChar.ToString(); - public string ImageUploadPath { get; set; } - - - /// - /// 设置监听端口,重启服务生效 - /// - //public string Port - //{ - // get { return this.port; } - // set - // { - // int p; - // if (string.IsNullOrEmpty(value) || !int.TryParse(value, out p)) - // { - // throw new Exception("给http监听器赋值的端口号无效!"); - // } - // this.port = value; - // } - //} - /// - /// http服务根目录 - /// - public string WebHomeDir - { - get { return this._webHomeDir; } - set - { - if (!Directory.Exists(value)) - throw new Exception("http服务器设置的根目录不存在!"); - this._webHomeDir = value; - } - } - /// - /// 服务器是否在运行 - /// - public bool IsRunning + get { return this._webHomeDir; } + set { - get { return (listener == null) ? false : listener.IsListening; } + if (!Directory.Exists(value)) + throw new Exception("http服务器设置的根目录不存在!"); + this._webHomeDir = value; } - #endregion + } + + /// + /// 服务器是否在运行 + /// + public bool IsRunning + { + get { return (listener == null) ? false : listener.IsListening; } + } + + #endregion + + #region - #region - public HttpServer( string host, string port, string webHomeDir, string imageUploadPath) + public HttpServer(string host, string port, string webHomeDir, string imageUploadPath) + { + this.Host = host; + this.port = port; + this._webHomeDir = webHomeDir; + ImageUploadPath = imageUploadPath; + listener = new HttpListener(); + } + + public bool AddPrefixes(string uriPrefix) + { + string uri = "http://" + uriPrefix + ":" + this.port + "/"; + if (listener.Prefixes.Contains(uri)) return false; + listener.Prefixes.Add(uri); + return true; + } + + /// + /// 启动服务 + /// + public void Start() + { + try { - - this.Host = host; - this.port = port; - this._webHomeDir = webHomeDir; - ImageUploadPath = imageUploadPath; - listener = new HttpListener(); - } + if (listener.IsListening) + return; + if (!string.IsNullOrEmpty(Host) && Host.Length > 0) + listener.Prefixes.Add("http://" + Host + ":" + this.port + "/"); //AGV/AGVAPI/agvCallback/ + else if (listener.Prefixes == null || listener.Prefixes.Count == 0) + listener.Prefixes.Add("http://localhost:" + this.port + "/"); + listener.Start(); - public bool AddPrefixes(string uriPrefix) + listenThread = new Thread(AcceptClient); + listenThread.Name = "signserver"; + listenThread.Start(); + Log("开启接口监听服务:" + this.port); + } + catch (Exception ex) { - string uri = "http://" + uriPrefix + ":" + this.port + "/"; - if (listener.Prefixes.Contains(uri)) return false; - listener.Prefixes.Add(uri); - return true; + LogUnit.Error(ex.Message); } + } - /// - /// 启动服务 - /// - public void Start() + /// + /// 停止服务 + /// + public void Stop() + { + try { - try - { - if (listener.IsListening) - return; - if (!string.IsNullOrEmpty(Host) && Host.Length > 0) - listener.Prefixes.Add("http://" + Host + ":" + this.port + "/"); //AGV/AGVAPI/agvCallback/ - else if (listener.Prefixes == null || listener.Prefixes.Count == 0) - listener.Prefixes.Add("http://localhost:" + this.port + "/"); - listener.Start(); - - listenThread = new Thread(AcceptClient); - listenThread.Name = "signserver"; - listenThread.Start(); - Log("开启接口监听服务:"+ this.port); - - } - catch (Exception ex) + if (listener != null) { - LogUnit.Error(ex.Message); + //listener.Close(); + //listener.Abort(); + listener.Stop(); } + } + catch (Exception ex) + { + LogUnit.Error(ex.Message); + } + } + /// + /// /接受客户端请求 + /// + private void AcceptClient() + { + //int maxThreadNum, portThreadNum; + ////线程池 + //int minThreadNum; + //ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum); + //ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum); + //Console.WriteLine("最大线程数:{0}", maxThreadNum); + //Console.WriteLine("最小空闲线程数:{0}", minThreadNum); - } - /// - /// 停止服务 - /// - public void Stop() + while (listener.IsListening) { try { - if (listener != null) - { - //listener.Close(); - //listener.Abort(); - listener.Stop(); - - } + HttpListenerContext context = listener.GetContext(); + //new Thread(HandleRequest).Start(context); + ThreadPool.QueueUserWorkItem(new WaitCallback(HandleRequest), context); } - catch (Exception ex) + catch { - LogUnit.Error(ex.Message); } } + } - /// - /// /接受客户端请求 - /// - void AcceptClient() - { - //int maxThreadNum, portThreadNum; - ////线程池 - //int minThreadNum; - //ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum); - //ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum); - //Console.WriteLine("最大线程数:{0}", maxThreadNum); - //Console.WriteLine("最小空闲线程数:{0}", minThreadNum); - - while (listener.IsListening) - { - try - { - HttpListenerContext context = listener.GetContext(); - //new Thread(HandleRequest).Start(context); - ThreadPool.QueueUserWorkItem(new WaitCallback(HandleRequest), context); - } - catch - { + #endregion - } - } + #region HandleRequest - } - #endregion - - #region HandleRequest - //处理客户端请求 - private void HandleRequest(object ctx) + //处理客户端请求 + private void HandleRequest(object ctx) + { + HttpListenerContext context = ctx as HttpListenerContext; + HttpListenerResponse response = context.Response; + HttpListenerRequest request = context.Request; + try { - HttpListenerContext context = ctx as HttpListenerContext; - HttpListenerResponse response = context.Response; - HttpListenerRequest request = context.Request; - try + context.Request.Headers.Add("Access-Control-Allow-Origin", "*"); + context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); + string rawUrl = System.Web.HttpUtility.UrlDecode(request.RawUrl); + int paramStartIndex = rawUrl.IndexOf('?'); + if (paramStartIndex > 0) + rawUrl = rawUrl.Substring(0, paramStartIndex); + else if (paramStartIndex == 0) + rawUrl = ""; + if (rawUrl.EndsWith("agvCallback")) { - context.Request.Headers.Add("Access-Control-Allow-Origin", "*"); - context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); - string rawUrl = System.Web.HttpUtility.UrlDecode(request.RawUrl); - int paramStartIndex = rawUrl.IndexOf('?'); - if (paramStartIndex > 0) - rawUrl = rawUrl.Substring(0, paramStartIndex); - else if (paramStartIndex == 0) - rawUrl = ""; - if ( rawUrl.EndsWith("agvCallback") ) { - - APICallBack apiCallBack = new APICallBack(); - - apiCallBack.reqCode = context.Request.QueryString["reqCode"]; - apiCallBack.taskCode = context.Request.QueryString["taskCode"]; - apiCallBack.method = context.Request.QueryString["method"]; - apiCallBack.wbCode = context.Request.QueryString["wbCode"]; - apiCallBack.robotCode = context.Request.QueryString["robotCode"]; - - //接收POST参数 2020-5-30 - Stream stream = context.Request.InputStream; - System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8); - //整理应该是接收到的值 - string body = reader.ReadToEnd(); - //FileUnit.Log(body); - //if (JsonUtil.JSONToObject(body)!=null) - //{ - // apiCallBack = JsonUnit.JSONToObject(body); - //} - - response.ContentType = "text/html;charset=utf-8"; - using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8)) - { - OnRecData?.Invoke(this, apiCallBack); - - string str = Newtonsoft.Json.JsonConvert.SerializeObject(new { Code = "0", Data = "调用成功", Message = "成功", ReqCode = apiCallBack.reqCode }); - writer.Write(str); - } + APICallBack apiCallBack = new APICallBack(); - ////Response - //context.Response.StatusCode = 200; - //context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); - //context.Response.ContentType = "application/json"; - //context.Response.ContentEncoding = Encoding.UTF8; - //byte[] buffer = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(new { Code = "0", Data= "调用成功", Message = "成功" , ReqCode ="",})); - //context.Response.ContentLength64 = buffer.Length; - //var output = context.Response.OutputStream; - //output.Write(buffer, 0, buffer.Length); - //output.Close(); - - } - else if (string.Compare(rawUrl, "/ImageUpload", true) == 0) - { - #region 上传图片 - string fileName = context.Request.QueryString["name"]; - string filePath = ImageUploadPath + "\\" + DateTime.Now.ToString("yyMMdd_HHmmss_ffff") - + Path.GetExtension(fileName).ToLower(); - using (var stream = request.InputStream) - { - using (var br = new BinaryReader(stream)) - { - WriteStreamToFile(br, filePath, request.ContentLength64); - } - } - response.ContentType = "text/html;charset=utf-8"; + apiCallBack.reqCode = context.Request.QueryString["reqCode"]; + apiCallBack.taskCode = context.Request.QueryString["taskCode"]; + apiCallBack.method = context.Request.QueryString["method"]; + apiCallBack.wbCode = context.Request.QueryString["wbCode"]; + apiCallBack.robotCode = context.Request.QueryString["robotCode"]; - using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8)) - { - writer.WriteLine("接收完成!"); - } + //接收POST参数 2020-5-30 + Stream stream = context.Request.InputStream; + System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8); + //整理应该是接收到的值 + string body = reader.ReadToEnd(); + //FileUnit.Log(body); + //if (JsonUtil.JSONToObject(body)!=null) + //{ + // apiCallBack = JsonUnit.JSONToObject(body); + //} - #endregion + response.ContentType = "text/html;charset=utf-8"; + using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8)) + { + OnRecData?.Invoke(this, apiCallBack); + + string str = Newtonsoft.Json.JsonConvert.SerializeObject(new { Code = "0", Data = "调用成功", Message = "成功", ReqCode = apiCallBack.reqCode }); + writer.Write(str); } - else + + ////Response + //context.Response.StatusCode = 200; + //context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); + //context.Response.ContentType = "application/json"; + //context.Response.ContentEncoding = Encoding.UTF8; + //byte[] buffer = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(new { Code = "0", Data= "调用成功", Message = "成功" , ReqCode ="",})); + //context.Response.ContentLength64 = buffer.Length; + //var output = context.Response.OutputStream; + //output.Write(buffer, 0, buffer.Length); + //output.Close(); + } + else if (string.Compare(rawUrl, "/ImageUpload", true) == 0) + { + #region 上传图片 + string fileName = context.Request.QueryString["name"]; + string filePath = ImageUploadPath + "\\" + DateTime.Now.ToString("yyMMdd_HHmmss_ffff") + + Path.GetExtension(fileName).ToLower(); + using (var stream = request.InputStream) { - #region 网页请求 - string InputStream = ""; - using (var streamReader = new StreamReader(request.InputStream)) - { - InputStream = streamReader.ReadToEnd(); - } - string filePath = ""; - if (string.IsNullOrEmpty(rawUrl) || rawUrl.Length == 0 || rawUrl == "/") - filePath = WebHomeDir + directorySeparatorChar + "Index.html"; - else - filePath = WebHomeDir + rawUrl.Replace("/", directorySeparatorChar); - if (!File.Exists(filePath)) - { - response.ContentLength64 = 0; - response.StatusCode = 404; - response.Abort(); - } - else + using (var br = new BinaryReader(stream)) { - response.StatusCode = 200; - string exeName = Path.GetExtension(filePath); - response.ContentType = GetContentType(exeName); - FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite); - int byteLength = (int)fileStream.Length; - byte[] fileBytes = new byte[byteLength]; - fileStream.Read(fileBytes, 0, byteLength); - fileStream.Close(); - fileStream.Dispose(); - response.ContentLength64 = byteLength; - response.OutputStream.Write(fileBytes, 0, byteLength); - response.OutputStream.Close(); + WriteStreamToFile(br, filePath, request.ContentLength64); } - #endregion } - } - catch (Exception ex) - { - LogUnit.Error(ex.Message); - response.StatusCode = 200; - response.ContentType = "text/plain"; + response.ContentType = "text/html;charset=utf-8"; + using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8)) { writer.WriteLine("接收完成!"); } + + #endregion } - try + else { - response.Close(); + #region 网页请求 + string InputStream = ""; + using (var streamReader = new StreamReader(request.InputStream)) + { + InputStream = streamReader.ReadToEnd(); + } + string filePath = ""; + if (string.IsNullOrEmpty(rawUrl) || rawUrl.Length == 0 || rawUrl == "/") + filePath = WebHomeDir + directorySeparatorChar + "Index.html"; + else + filePath = WebHomeDir + rawUrl.Replace("/", directorySeparatorChar); + if (!File.Exists(filePath)) + { + response.ContentLength64 = 0; + response.StatusCode = 404; + response.Abort(); + } + else + { + response.StatusCode = 200; + string exeName = Path.GetExtension(filePath); + response.ContentType = GetContentType(exeName); + FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite); + int byteLength = (int)fileStream.Length; + byte[] fileBytes = new byte[byteLength]; + fileStream.Read(fileBytes, 0, byteLength); + fileStream.Close(); + fileStream.Dispose(); + response.ContentLength64 = byteLength; + response.OutputStream.Write(fileBytes, 0, byteLength); + response.OutputStream.Close(); + } + #endregion } - catch (Exception ex) + } + catch (Exception ex) + { + LogUnit.Error(ex.Message); + response.StatusCode = 200; + response.ContentType = "text/plain"; + using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8)) { - LogUnit.Error(ex.Message); + writer.WriteLine("接收完成!"); } } - #endregion - - #region GetContentType - /// - /// 获取文件对应MIME类型 - /// - /// 文件扩展名,如.jpg - /// - protected string GetContentType(string fileExtention) + try { - if (string.Compare(fileExtention, ".html", true) == 0 - || string.Compare(fileExtention, ".htm", true) == 0) - return "text/html;charset=utf-8"; - else if (string.Compare(fileExtention, ".js", true) == 0) - return "application/javascript"; - else if (string.Compare(fileExtention, ".css", true) == 0) - return "text/css"; - else if (string.Compare(fileExtention, ".png", true) == 0) - return "image/png"; - else if (string.Compare(fileExtention, ".jpg", true) == 0 || string.Compare(fileExtention, ".jpeg", true) == 0) - return "image/jpeg"; - else if (string.Compare(fileExtention, ".gif", true) == 0) - return "image/gif"; - else if (string.Compare(fileExtention, ".swf", true) == 0) - return "application/x-shockwave-flash"; - else if (string.Compare(fileExtention, ".pdf", true) == 0) - return "application/pdf"; - else - return "";//application/octet-stream + response.Close(); } - #endregion + catch (Exception ex) + { + LogUnit.Error(ex.Message); + } + } + + #endregion + + #region GetContentType + + /// + /// 获取文件对应MIME类型 + /// + /// 文件扩展名,如.jpg + /// + protected string GetContentType(string fileExtention) + { + if (string.Compare(fileExtention, ".html", true) == 0 + || string.Compare(fileExtention, ".htm", true) == 0) + return "text/html;charset=utf-8"; + else if (string.Compare(fileExtention, ".js", true) == 0) + return "application/javascript"; + else if (string.Compare(fileExtention, ".css", true) == 0) + return "text/css"; + else if (string.Compare(fileExtention, ".png", true) == 0) + return "image/png"; + else if (string.Compare(fileExtention, ".jpg", true) == 0 || string.Compare(fileExtention, ".jpeg", true) == 0) + return "image/jpeg"; + else if (string.Compare(fileExtention, ".gif", true) == 0) + return "image/gif"; + else if (string.Compare(fileExtention, ".swf", true) == 0) + return "application/x-shockwave-flash"; + else if (string.Compare(fileExtention, ".pdf", true) == 0) + return "application/pdf"; + else + return "";//application/octet-stream + } + + #endregion + + #region WriteStreamToFile - #region WriteStreamToFile - //const int ChunkSize = 1024 * 1024; - private void WriteStreamToFile(BinaryReader br, string fileName, long length) + //const int ChunkSize = 1024 * 1024; + private void WriteStreamToFile(BinaryReader br, string fileName, long length) + { + byte[] fileContents = new byte[] { }; + var bytes = new byte[length]; + int i = 0; + while ((i = br.Read(bytes, 0, (int)length)) != 0) { - byte[] fileContents = new byte[] { }; - var bytes = new byte[length]; - int i = 0; - while ((i = br.Read(bytes, 0, (int)length)) != 0) - { - byte[] arr = new byte[fileContents.LongLength + i]; - fileContents.CopyTo(arr, 0); - Array.Copy(bytes, 0, arr, fileContents.Length, i); - fileContents = arr; - } + byte[] arr = new byte[fileContents.LongLength + i]; + fileContents.CopyTo(arr, 0); + Array.Copy(bytes, 0, arr, fileContents.Length, i); + fileContents = arr; + } - using (var fs = new FileStream(fileName, FileMode.Create)) + using (var fs = new FileStream(fileName, FileMode.Create)) + { + using (var bw = new BinaryWriter(fs)) { - using (var bw = new BinaryWriter(fs)) - { - bw.Write(fileContents); - } + bw.Write(fileContents); } } - #endregion - public void Log(string msg, bool isErr = false) - { - //(msg, isErr); - } } -} + + #endregion + + public void Log(string msg, bool isErr = false) + { + //(msg, isErr); + } +} \ No newline at end of file diff --git a/EC.Util/Net/NetUnit.cs b/EC.Util/Net/NetUnit.cs index 0efb98b..b9a8686 100644 --- a/EC.Util/Net/NetUnit.cs +++ b/EC.Util/Net/NetUnit.cs @@ -1,657 +1,623 @@ -using System; -using System.Collections.Generic; -using System.Linq; +using System.Net; using System.Text; using System.Text.RegularExpressions; -using System.Net; -using System.IO; -namespace System -{ +namespace EC.Util.Net; + +/// +/// 网络操作单元 +/// +public partial class NetUnit +{ + #region 获取主机名称 + /// - /// 网络操作单元 + /// 获取本地机器名称 /// - public partial class NetUnit + /// 机器名称 + public static string GetHostName() { + string hostName = ""; + try + { + hostName = Dns.GetHostName(); + return hostName; + } + catch + { + return null; + } + } + + #endregion 获取主机名称 - #region 获取主机名称 - /// - /// 获取本地机器名称 - /// - /// 机器名称 - public static string GetHostName() + #region 获取本地主机IP + + /// + /// 获取本地机器IP + /// + /// IP地址 + public static string GetHostIp() + { + string localIp = ""; + try { - string hostName = ""; - try + System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList; + for (int i = 0; i < addressList.Length; i++) { - hostName = Dns.GetHostName(); - return hostName; - } - catch - { - return null; + localIp += addressList[i].ToString(); } + return localIp; } - #endregion - - #region 获取本地主机IP - /// - /// 获取本地机器IP - /// - /// IP地址 - public static string GetHostIp() + catch { - string localIp = ""; - try - { - System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList; - for (int i = 0; i < addressList.Length; i++) - { - localIp += addressList[i].ToString(); - } - return localIp; - } - catch - { - return null; - } - + return null; } - #endregion + } - #region 穿过代理服务器获得Ip地址,如果有多个IP,则第一个是用户的真实IP,其余全是代理的IP,用逗号隔开 - //public static string getRealIp() - //{ - // string UserIP; - // if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"]!=null) //得到穿过代理服务器的ip地址 - // { + #endregion 获取本地主机IP - // UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); - // } - // else + #region 穿过代理服务器获得Ip地址,如果有多个IP,则第一个是用户的真实IP,其余全是代理的IP,用逗号隔开 + + //public static string getRealIp() + //{ + // string UserIP; + // if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"]!=null) //得到穿过代理服务器的ip地址 + // { + // UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); + // } + // else + // { + // UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString(); + // } + // return UserIP; + //} + + #endregion 穿过代理服务器获得Ip地址,如果有多个IP,则第一个是用户的真实IP,其余全是代理的IP,用逗号隔开 + + #region 获取主机MAC地址 + + /// + /// 获取本机MAC地址 + /// + /// string null + public static string GetHostMac() + { + //string mac = ""; + //try + //{ + // ManagementClass mc; + // mc=new ManagementClass("Win32_NetworkAdapterConfiguration"); + // ManagementObjectCollection moc=mc.GetInstances(); + // foreach(ManagementObject mo in moc) // { - // UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString(); + // if(mo["IPEnabled"].ToString()=="True") + // mac=mo["MacAddress"].ToString(); // } - // return UserIP; + // return mac; //} - #endregion + //catch + //{ + // return null; + //} + return null; + } + #endregion 获取主机MAC地址 - #region 获取主机MAC地址 - /// - /// 获取本机MAC地址 - /// - /// string null - public static string GetHostMac() - { - //string mac = ""; - //try - //{ - // ManagementClass mc; - // mc=new ManagementClass("Win32_NetworkAdapterConfiguration"); - // ManagementObjectCollection moc=mc.GetInstances(); - // foreach(ManagementObject mo in moc) - // { - // if(mo["IPEnabled"].ToString()=="True") - // mac=mo["MacAddress"].ToString(); - // } - // return mac; - //} - //catch - //{ - // return null; - //} - return null; + #region 获取本机IP - } - #endregion + public static string GetLocalIp() + { + //Page.Request.UserHostName + return null; + } + + #endregion 获取本机IP - #region 获取本机IP - public static string GetLocalIp() + /// + /// C# 验证IP + /// + /// + /// + public static bool IsIP(string ip) + { + string pattern = @"(((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))"; + Regex objRe = new Regex(pattern); + Match objMa = objRe.Match(ip); + if (!objMa.Success) { - //Page.Request.UserHostName - return null; + return false; } - #endregion - - - /// - /// C# 验证IP - /// - /// - /// - public static bool IsIP(string ip) + else return true; + } + + public static string PingResult(string ip) + { + System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); + System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions(); + options.DontFragment = true; + string data = "Lxc"; + byte[] buffer = Encoding.ASCII.GetBytes(data); + //Wait seconds for a reply. + int timeout = 100; + + System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options); + return reply.Status.ToString(); + } + + #region 获取指定WEB页面 + + /// GET方法获取页面 + /// 函数名:GetWebUrl + /// 功能描述:WebClient 获取页面 + /// 处理流程: + /// 算法描述: + /// 作 者: lxc + /// 日 期: 2012-10-09 + /// 修 改: + /// 日 期: + /// 版 本: + public static string GetWebUrl(string strurl) + { + WebClient webClient = new WebClient(); + try { - string pattern = @"(((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))"; - Regex objRe = new Regex(pattern); - Match objMa = objRe.Match(ip); - if(!objMa.Success) - { - return false; - } - else return true; + webClient.Credentials = CredentialCache.DefaultCredentials; + Byte[] pageData = webClient.DownloadData(strurl); + //string pageHtml = Encoding.UTF8.GetString(pageData); + string pageHtml = Encoding.Default.GetString(pageData); + return pageHtml; } - public static string PingResult(string ip) + catch (WebException webEx) { - System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); - System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions(); - options.DontFragment = true; - string data = "Lxc"; - byte[] buffer = Encoding.ASCII.GetBytes(data); - //Wait seconds for a reply. - int timeout = 100; - - System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options); - return reply.Status.ToString(); - - + return "error_GetWebUrl:" + webEx.ToString(); } - - #region 获取指定WEB页面 - /// GET方法获取页面 - /// 函数名:GetWebUrl - /// 功能描述:WebClient 获取页面 - /// 处理流程: - /// 算法描述: - /// 作 者: lxc - /// 日 期: 2012-10-09 - /// 修 改: - /// 日 期: - /// 版 本: - public static string GetWebUrl(string strurl) + finally { - WebClient webClient = new WebClient(); - try - { - webClient.Credentials = CredentialCache.DefaultCredentials; - Byte[] pageData = webClient.DownloadData(strurl); - //string pageHtml = Encoding.UTF8.GetString(pageData); - string pageHtml = Encoding.Default.GetString(pageData); - return pageHtml; + webClient = null; + } + } - } - catch (WebException webEx) - { - return "error_GetWebUrl:" + webEx.ToString(); - } - finally - { - webClient = null; - } + #endregion 获取指定WEB页面 + #region PostUrl(String url, String paramList) - } - #endregion - - #region PostUrl(String url, String paramList) - /// - /// POST方法获取页面 - /// - /// - /// 格式: a=xxx&b=xxx&c=xxx - /// - public static string PostUrl(String url, String paramList) + /// + /// POST方法获取页面 + /// + /// + /// 格式: a=xxx&b=xxx&c=xxx + /// + public static string PostUrl(String url, String paramList) + { + HttpWebResponse res = null; + string strResult = ""; + try { - HttpWebResponse res = null; - string strResult = ""; - try + HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); + req.Method = "POST"; + req.KeepAlive = true; + req.ContentType = "application/x-www-form-urlencoded"; + //req.UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)"; + CookieContainer cookieCon = new CookieContainer(); + req.CookieContainer = cookieCon; + StringBuilder UrlEncoded = new StringBuilder(); + Char[] reserved = { '?', '=', '&' }; + byte[] SomeBytes = null; + if (paramList != null) { - - HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); - req.Method = "POST"; - req.KeepAlive = true; - req.ContentType = "application/x-www-form-urlencoded"; - //req.UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)"; - CookieContainer cookieCon = new CookieContainer(); - req.CookieContainer = cookieCon; - StringBuilder UrlEncoded = new StringBuilder(); - Char[] reserved = { '?', '=', '&' }; - byte[] SomeBytes = null; - if (paramList != null) + int i = 0, j; + while (i < paramList.Length) { - int i = 0, j; - while (i < paramList.Length) + j = paramList.IndexOfAny(reserved, i); + if (j == -1) { - j = paramList.IndexOfAny(reserved, i); - if (j == -1) - { - // UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, paramList.Length-i))); - UrlEncoded.Append((paramList.Substring(i, paramList.Length - i))); - break; - } - // UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, j-i))); - UrlEncoded.Append((paramList.Substring(i, j - i))); - UrlEncoded.Append(paramList.Substring(j, 1)); - i = j + 1; + // UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, paramList.Length-i))); + UrlEncoded.Append((paramList.Substring(i, paramList.Length - i))); + break; } - SomeBytes = Encoding.Default.GetBytes(UrlEncoded.ToString()); - req.ContentLength = SomeBytes.Length; - Stream newStream = req.GetRequestStream(); - newStream.Write(SomeBytes, 0, SomeBytes.Length); - newStream.Close(); - } - else - { - req.ContentLength = 0; - } - res = (HttpWebResponse)req.GetResponse(); - Stream ReceiveStream = res.GetResponseStream(); - // Encoding encode = System.Text.Encoding.Default;//GetEncoding("utf-8"); - string encodeheader = res.ContentType; - string encodestr = System.Text.Encoding.Default.HeaderName; - if ((encodeheader.IndexOf("charset=") >= 0) && (encodeheader.IndexOf("charset=GBK") == -1) && (encodeheader.IndexOf("charset=gbk") == -1)) - { - int i = encodeheader.IndexOf("charset="); - encodestr = encodeheader.Substring(i + 8); - } - Encoding encode = System.Text.Encoding.GetEncoding(encodestr);//GetEncoding("utf-8"); - - StreamReader sr = new StreamReader(ReceiveStream, encode); - Char[] read = new Char[256]; - int count = sr.Read(read, 0, 256); - while (count > 0) - { - String str = new String(read, 0, count); - strResult += str; - count = sr.Read(read, 0, 256); + // UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, j-i))); + UrlEncoded.Append((paramList.Substring(i, j - i))); + UrlEncoded.Append(paramList.Substring(j, 1)); + i = j + 1; } + SomeBytes = Encoding.Default.GetBytes(UrlEncoded.ToString()); + req.ContentLength = SomeBytes.Length; + Stream newStream = req.GetRequestStream(); + newStream.Write(SomeBytes, 0, SomeBytes.Length); + newStream.Close(); } - catch (Exception e) + else { - strResult = e.ToString(); + req.ContentLength = 0; } - finally + res = (HttpWebResponse)req.GetResponse(); + Stream ReceiveStream = res.GetResponseStream(); + // Encoding encode = System.Text.Encoding.Default;//GetEncoding("utf-8"); + string encodeheader = res.ContentType; + string encodestr = System.Text.Encoding.Default.HeaderName; + if ((encodeheader.IndexOf("charset=") >= 0) && (encodeheader.IndexOf("charset=GBK") == -1) && (encodeheader.IndexOf("charset=gbk") == -1)) { - if (res != null) - { - res.Close(); - } + int i = encodeheader.IndexOf("charset="); + encodestr = encodeheader.Substring(i + 8); } - return strResult; - } + Encoding encode = System.Text.Encoding.GetEncoding(encodestr);//GetEncoding("utf-8"); - #endregion - - - - - #region 下载指定WEB页面 - /// GET方法获取页面 - /// 函数名:GetFileUrl - /// 功能描述:WebClient 下载文件 - /// 处理流程: - /// 算法描述: - /// 作 者: lxc - /// 日 期: 2012-10-09 - /// 修 改: - /// 日 期: - /// 版 本: - public static Boolean GetFileUrl(string strurl, string filename) - { - try + StreamReader sr = new StreamReader(ReceiveStream, encode); + Char[] read = new Char[256]; + int count = sr.Read(read, 0, 256); + while (count > 0) { - - WebClient webClient = new WebClient(); - // webClient.Credentials = CredentialCache.DefaultCredentials; - webClient.DownloadFile(strurl, filename); - return true; - + String str = new String(read, 0, count); + strResult += str; + count = sr.Read(read, 0, 256); } - catch (WebException webex) + } + catch (Exception e) + { + strResult = e.ToString(); + } + finally + { + if (res != null) { - return false;// "error_GetWebUrl:" + webEx.ToString(); + res.Close(); } + } + return strResult; + } + #endregion PostUrl(String url, String paramList) + + #region 下载指定WEB页面 + + /// GET方法获取页面 + /// 函数名:GetFileUrl + /// 功能描述:WebClient 下载文件 + /// 处理流程: + /// 算法描述: + /// 作 者: lxc + /// 日 期: 2012-10-09 + /// 修 改: + /// 日 期: + /// 版 本: + public static Boolean GetFileUrl(string strurl, string filename) + { + try + { + WebClient webClient = new WebClient(); + // webClient.Credentials = CredentialCache.DefaultCredentials; + webClient.DownloadFile(strurl, filename); + return true; } - #endregion + catch (WebException webex) + { + return false;// "error_GetWebUrl:" + webEx.ToString(); + } + } + #endregion 下载指定WEB页面 - #region 获取图片 + #region 获取图片 + public static Stream GetImage(String url) + { + HttpWebResponse res = null; - public static Stream GetImage(String url) + try { + HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); - HttpWebResponse res = null; - - - try - { - HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); + res = (HttpWebResponse)req.GetResponse(); + Stream ReceiveStream = res.GetResponseStream(); + return ReceiveStream; + } + catch + { + return null; + } + finally + { + } + } + /// GET方法获取页面 + /// 函数名:GetImage + /// 功能描述:GET方法获取页面 + /// 处理流程: + /// 算法描述: + /// 作 者: 杨栋 + /// 日 期: 2006-11-21 09:00 + /// 修 改: 2007-01-29 17:00 2006-12-05 17:00 + /// 日 期: + /// 版 本: + /// + #region GetImage(String url,string cookieheader) - res = (HttpWebResponse)req.GetResponse(); - Stream ReceiveStream = res.GetResponseStream(); - return ReceiveStream; + /// + /// + /// + /// 目标url + /// 输入Cookie + /// + public static byte[] GetImage(String url, string cookieheader) + { + // outcookieheader=""; - } - catch - { - return null; - } - finally - { - } - } + HttpWebResponse res = null; - /// GET方法获取页面 - /// 函数名:GetImage - /// 功能描述:GET方法获取页面 - /// 处理流程: - /// 算法描述: - /// 作 者: 杨栋 - /// 日 期: 2006-11-21 09:00 - /// 修 改: 2007-01-29 17:00 2006-12-05 17:00 - /// 日 期: - /// 版 本: - /// - #region GetImage(String url,string cookieheader) - /// - /// - /// - /// 目标url - /// 输入Cookie - /// - public static byte[] GetImage(String url, string cookieheader) + try { - // outcookieheader=""; - - HttpWebResponse res = null; - - - try + HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); + // req.Method = "GET"; + // req.ContentType = "application/x-www-form-urlencoded"; + //req.UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)"; + // CookieContainer cookieCon = new CookieContainer(); + // + // // string name=cookieheader.Substring(0,cookieheader.IndexOf("=")); + // // string key=cookieheader.Substring(cookieheader.IndexOf("=")+1,cookieheader.Length-cookieheader.IndexOf("=")-1); + // // cookieCon.Add(new Uri(url),new Cookie(name,key)); + // + // + // req.CookieContainer = cookieCon; + // if ((cookieheader.Length>0 )&(cookieheader.IndexOf("=")>0)) + // { + // req.CookieContainer.SetCookies(new Uri(url),cookieheader); + // } + + //为请求加入cookies + CookieContainer cookieCon = new CookieContainer(); + // req.CookieContainer = cookieCon; + //取得cookies 集合 + string[] ls_cookies = cookieheader.Split(';'); + if (ls_cookies.Length <= 1) //如果有一个或没有cookies 就采用下面的方法。 { - HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); - // req.Method = "GET"; - // req.ContentType = "application/x-www-form-urlencoded"; - //req.UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)"; - // CookieContainer cookieCon = new CookieContainer(); - // - // // string name=cookieheader.Substring(0,cookieheader.IndexOf("=")); - // // string key=cookieheader.Substring(cookieheader.IndexOf("=")+1,cookieheader.Length-cookieheader.IndexOf("=")-1); - // // cookieCon.Add(new Uri(url),new Cookie(name,key)); - // - // - // req.CookieContainer = cookieCon; - // if ((cookieheader.Length>0 )&(cookieheader.IndexOf("=")>0)) - // { - // req.CookieContainer.SetCookies(new Uri(url),cookieheader); - // } - - - //为请求加入cookies - CookieContainer cookieCon = new CookieContainer(); - // req.CookieContainer = cookieCon; - //取得cookies 集合 - string[] ls_cookies = cookieheader.Split(';'); - if (ls_cookies.Length <= 1) //如果有一个或没有cookies 就采用下面的方法。 + req.CookieContainer = cookieCon; + if ((cookieheader.Length > 0) & (cookieheader.IndexOf("=") > 0)) { - req.CookieContainer = cookieCon; - if ((cookieheader.Length > 0) & (cookieheader.IndexOf("=") > 0)) - { - req.CookieContainer.SetCookies(new Uri(url), cookieheader); - } + req.CookieContainer.SetCookies(new Uri(url), cookieheader); } - else - { - //如果是多个cookie 就分别加入 cookies 容器。 - ////////////////////////////////// - string[] ls_cookie = null; - - for (int i = 0; i < ls_cookies.Length; i++) - { - ls_cookie = ls_cookies[i].Split('='); - // cookieCon.Add(new Uri(url),new Cookie(ls_cookie[0].ToString().Trim(),ls_cookie[1].ToString().Trim())); - cookieCon.Add(new Uri(url), new Cookie(ls_cookie[0].ToString().Trim(), ls_cookies[i].Substring(ls_cookies[i].IndexOf("=") + 1))); - } - req.CookieContainer = cookieCon; + } + else + { + //如果是多个cookie 就分别加入 cookies 容器。 + ////////////////////////////////// + string[] ls_cookie = null; - //////////////////////////////////// + for (int i = 0; i < ls_cookies.Length; i++) + { + ls_cookie = ls_cookies[i].Split('='); + // cookieCon.Add(new Uri(url),new Cookie(ls_cookie[0].ToString().Trim(),ls_cookie[1].ToString().Trim())); + cookieCon.Add(new Uri(url), new Cookie(ls_cookie[0].ToString().Trim(), ls_cookies[i].Substring(ls_cookies[i].IndexOf("=") + 1))); } + req.CookieContainer = cookieCon; + //////////////////////////////////// + } + res = (HttpWebResponse)req.GetResponse(); + Stream ReceiveStream = res.GetResponseStream(); - res = (HttpWebResponse)req.GetResponse(); - Stream ReceiveStream = res.GetResponseStream(); - - - byte[] mybytes = new byte[4096]; - - int count = ReceiveStream.Read(mybytes, 0, 4096); - - byte[] image = new byte[count]; + byte[] mybytes = new byte[4096]; - Array.Copy(mybytes, image, count); + int count = ReceiveStream.Read(mybytes, 0, 4096); + byte[] image = new byte[count]; + Array.Copy(mybytes, image, count); - if (res != null) - { - res.Close(); - } - return image; - } - finally + if (res != null) { + res.Close(); } + return image; + } + finally + { } + } - #endregion + #endregion GetImage(String url,string cookieheader) - #region GetImage(String url,string cookieheader,out string outcookieheader,string Header_Referer) - /// - /// - /// - /// 目标url - /// 输入Cookie - /// - public static byte[] GetImage(String url, string cookieheader, out string outcookieheader, string Header_Referer) - { - // outcookieheader=""; + #region GetImage(String url,string cookieheader,out string outcookieheader,string Header_Referer) - HttpWebResponse res = null; + /// + /// + /// + /// 目标url + /// 输入Cookie + /// + public static byte[] GetImage(String url, string cookieheader, out string outcookieheader, string Header_Referer) + { + // outcookieheader=""; + HttpWebResponse res = null; - try + try + { + HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); + if (Header_Referer.Length > 1) { - HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); - if (Header_Referer.Length > 1) - { - req.Referer = Header_Referer; - } - // req.Method = "GET"; - // req.ContentType = "application/x-www-form-urlencoded"; - //req.UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)"; - // CookieContainer cookieCon = new CookieContainer(); - // - // // string name=cookieheader.Substring(0,cookieheader.IndexOf("=")); - // // string key=cookieheader.Substring(cookieheader.IndexOf("=")+1,cookieheader.Length-cookieheader.IndexOf("=")-1); - // // cookieCon.Add(new Uri(url),new Cookie(name,key)); - // - // - // req.CookieContainer = cookieCon; - // if ((cookieheader.Length>0 )&(cookieheader.IndexOf("=")>0)) - // { - // req.CookieContainer.SetCookies(new Uri(url),cookieheader); - // } - - //为请求加入cookies - CookieContainer cookieCon = new CookieContainer(); - // req.CookieContainer = cookieCon; - //取得cookies 集合 - string[] ls_cookies = cookieheader.Split(';'); - if (ls_cookies.Length <= 1) //如果有一个或没有cookies 就采用下面的方法。 + req.Referer = Header_Referer; + } + // req.Method = "GET"; + // req.ContentType = "application/x-www-form-urlencoded"; + //req.UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)"; + // CookieContainer cookieCon = new CookieContainer(); + // + // // string name=cookieheader.Substring(0,cookieheader.IndexOf("=")); + // // string key=cookieheader.Substring(cookieheader.IndexOf("=")+1,cookieheader.Length-cookieheader.IndexOf("=")-1); + // // cookieCon.Add(new Uri(url),new Cookie(name,key)); + // + // + // req.CookieContainer = cookieCon; + // if ((cookieheader.Length>0 )&(cookieheader.IndexOf("=")>0)) + // { + // req.CookieContainer.SetCookies(new Uri(url),cookieheader); + // } + + //为请求加入cookies + CookieContainer cookieCon = new CookieContainer(); + // req.CookieContainer = cookieCon; + //取得cookies 集合 + string[] ls_cookies = cookieheader.Split(';'); + if (ls_cookies.Length <= 1) //如果有一个或没有cookies 就采用下面的方法。 + { + req.CookieContainer = cookieCon; + if ((cookieheader.Length > 0) & (cookieheader.IndexOf("=") > 0)) { - req.CookieContainer = cookieCon; - if ((cookieheader.Length > 0) & (cookieheader.IndexOf("=") > 0)) - { - req.CookieContainer.SetCookies(new Uri(url), cookieheader); - } + req.CookieContainer.SetCookies(new Uri(url), cookieheader); } - else - { - //如果是多个cookie 就分别加入 cookies 容器。 - ////////////////////////////////// - string[] ls_cookie = null; - - for (int i = 0; i < ls_cookies.Length; i++) - { - ls_cookie = ls_cookies[i].Split('='); - // cookieCon.Add(new Uri(url),new Cookie(ls_cookie[0].ToString().Trim(),ls_cookie[1].ToString().Trim())); - cookieCon.Add(new Uri(url), new Cookie(ls_cookie[0].ToString().Trim(), ls_cookies[i].Substring(ls_cookies[i].IndexOf("=") + 1))); - } - req.CookieContainer = cookieCon; + } + else + { + //如果是多个cookie 就分别加入 cookies 容器。 + ////////////////////////////////// + string[] ls_cookie = null; - //////////////////////////////////// + for (int i = 0; i < ls_cookies.Length; i++) + { + ls_cookie = ls_cookies[i].Split('='); + // cookieCon.Add(new Uri(url),new Cookie(ls_cookie[0].ToString().Trim(),ls_cookie[1].ToString().Trim())); + cookieCon.Add(new Uri(url), new Cookie(ls_cookie[0].ToString().Trim(), ls_cookies[i].Substring(ls_cookies[i].IndexOf("=") + 1))); } + req.CookieContainer = cookieCon; + //////////////////////////////////// + } + res = (HttpWebResponse)req.GetResponse(); + Stream ReceiveStream = res.GetResponseStream(); - res = (HttpWebResponse)req.GetResponse(); - Stream ReceiveStream = res.GetResponseStream(); - - outcookieheader = req.CookieContainer.GetCookieHeader(new Uri(url));//获得cookie + outcookieheader = req.CookieContainer.GetCookieHeader(new Uri(url));//获得cookie - if (outcookieheader.Length < 2) + if (outcookieheader.Length < 2) + { + try { - try - { - outcookieheader = res.Headers["Set-Cookie"]; - outcookieheader = outcookieheader.Substring(0, outcookieheader.IndexOf(";")); - } - catch - { - outcookieheader = ""; - } + outcookieheader = res.Headers["Set-Cookie"]; + outcookieheader = outcookieheader.Substring(0, outcookieheader.IndexOf(";")); } + catch + { + outcookieheader = ""; + } + } + byte[] mybytes = new byte[4096]; - byte[] mybytes = new byte[4096]; - - int count = ReceiveStream.Read(mybytes, 0, 4096); - - byte[] image = new byte[count]; - - Array.Copy(mybytes, image, count); + int count = ReceiveStream.Read(mybytes, 0, 4096); + byte[] image = new byte[count]; + Array.Copy(mybytes, image, count); - if (res != null) - { - res.Close(); - } - return image; - } - finally + if (res != null) { + res.Close(); } + return image; } - - #endregion - - #region GetImage(String url,string cookieheader,string Header_Referer) - /// - /// - /// - /// 目标url - /// 输入Cookie - /// 包头 Referer - /// - public static byte[] GetImage(String url, string cookieheader, string Header_Referer) + finally { - // outcookieheader=""; + } + } - HttpWebResponse res = null; + #endregion GetImage(String url,string cookieheader,out string outcookieheader,string Header_Referer) + #region GetImage(String url,string cookieheader,string Header_Referer) - try + /// + /// + /// + /// 目标url + /// 输入Cookie + /// 包头 Referer + /// + public static byte[] GetImage(String url, string cookieheader, string Header_Referer) + { + // outcookieheader=""; + + HttpWebResponse res = null; + + try + { + HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); + if (Header_Referer.Length > 1) { - HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); - if (Header_Referer.Length > 1) - { - req.Referer = Header_Referer; - } - // req.Method = "GET"; - // req.ContentType = "application/x-www-form-urlencoded"; - //req.UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)"; - // CookieContainer cookieCon = new CookieContainer(); - // - // // string name=cookieheader.Substring(0,cookieheader.IndexOf("=")); - // // string key=cookieheader.Substring(cookieheader.IndexOf("=")+1,cookieheader.Length-cookieheader.IndexOf("=")-1); - // // cookieCon.Add(new Uri(url),new Cookie(name,key)); - // - // - // req.CookieContainer = cookieCon; - // if ((cookieheader.Length>0 )&(cookieheader.IndexOf("=")>0)) - // { - // req.CookieContainer.SetCookies(new Uri(url),cookieheader); - // } - - //为请求加入cookies - CookieContainer cookieCon = new CookieContainer(); - // req.CookieContainer = cookieCon; - //取得cookies 集合 - string[] ls_cookies = cookieheader.Split(';'); - if (ls_cookies.Length <= 1) //如果有一个或没有cookies 就采用下面的方法。 + req.Referer = Header_Referer; + } + // req.Method = "GET"; + // req.ContentType = "application/x-www-form-urlencoded"; + //req.UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)"; + // CookieContainer cookieCon = new CookieContainer(); + // + // // string name=cookieheader.Substring(0,cookieheader.IndexOf("=")); + // // string key=cookieheader.Substring(cookieheader.IndexOf("=")+1,cookieheader.Length-cookieheader.IndexOf("=")-1); + // // cookieCon.Add(new Uri(url),new Cookie(name,key)); + // + // + // req.CookieContainer = cookieCon; + // if ((cookieheader.Length>0 )&(cookieheader.IndexOf("=")>0)) + // { + // req.CookieContainer.SetCookies(new Uri(url),cookieheader); + // } + + //为请求加入cookies + CookieContainer cookieCon = new CookieContainer(); + // req.CookieContainer = cookieCon; + //取得cookies 集合 + string[] ls_cookies = cookieheader.Split(';'); + if (ls_cookies.Length <= 1) //如果有一个或没有cookies 就采用下面的方法。 + { + req.CookieContainer = cookieCon; + if ((cookieheader.Length > 0) & (cookieheader.IndexOf("=") > 0)) { - req.CookieContainer = cookieCon; - if ((cookieheader.Length > 0) & (cookieheader.IndexOf("=") > 0)) - { - req.CookieContainer.SetCookies(new Uri(url), cookieheader); - } + req.CookieContainer.SetCookies(new Uri(url), cookieheader); } - else - { - //如果是多个cookie 就分别加入 cookies 容器。 - ////////////////////////////////// - string[] ls_cookie = null; - - for (int i = 0; i < ls_cookies.Length; i++) - { - ls_cookie = ls_cookies[i].Split('='); - // cookieCon.Add(new Uri(url),new Cookie(ls_cookie[0].ToString().Trim(),ls_cookie[1].ToString().Trim())); - cookieCon.Add(new Uri(url), new Cookie(ls_cookie[0].ToString().Trim(), ls_cookies[i].Substring(ls_cookies[i].IndexOf("=") + 1))); - } - req.CookieContainer = cookieCon; + } + else + { + //如果是多个cookie 就分别加入 cookies 容器。 + ////////////////////////////////// + string[] ls_cookie = null; - //////////////////////////////////// + for (int i = 0; i < ls_cookies.Length; i++) + { + ls_cookie = ls_cookies[i].Split('='); + // cookieCon.Add(new Uri(url),new Cookie(ls_cookie[0].ToString().Trim(),ls_cookie[1].ToString().Trim())); + cookieCon.Add(new Uri(url), new Cookie(ls_cookie[0].ToString().Trim(), ls_cookies[i].Substring(ls_cookies[i].IndexOf("=") + 1))); } + req.CookieContainer = cookieCon; + //////////////////////////////////// + } + res = (HttpWebResponse)req.GetResponse(); + Stream ReceiveStream = res.GetResponseStream(); - res = (HttpWebResponse)req.GetResponse(); - Stream ReceiveStream = res.GetResponseStream(); - - - byte[] mybytes = new byte[4096]; - - int count = ReceiveStream.Read(mybytes, 0, 4096); - - byte[] image = new byte[count]; + byte[] mybytes = new byte[4096]; - Array.Copy(mybytes, image, count); + int count = ReceiveStream.Read(mybytes, 0, 4096); + byte[] image = new byte[count]; + Array.Copy(mybytes, image, count); - if (res != null) - { - res.Close(); - } - return image; - } - finally + if (res != null) { + res.Close(); } + return image; } + finally + { + } + } - #endregion - - #region GetImage(String url,string cookieheader,string Header_Referer,string Header_UserAgent,string http_type) - - #endregion - + #endregion GetImage(String url,string cookieheader,string Header_Referer) - #endregion - } -} + #endregion 获取图片 +} \ No newline at end of file diff --git a/EC.Util/Zmq/ZmqUtil.cs b/EC.Util/Zmq/ZmqUtil.cs index cbdc72a..a21f87b 100644 --- a/EC.Util/Zmq/ZmqUtil.cs +++ b/EC.Util/Zmq/ZmqUtil.cs @@ -1,6 +1,6 @@ namespace EC.Util.Zmq; -internal class ZmqUtil +public class ZmqUtil { //#region Fields diff --git a/JiLinApp.Biz/TransmitAlarm/Common/Config.cs b/JiLinApp.Biz/TransmitAlarm/Common/Config.cs index 6427bb3..49e0095 100644 --- a/JiLinApp.Biz/TransmitAlarm/Common/Config.cs +++ b/JiLinApp.Biz/TransmitAlarm/Common/Config.cs @@ -11,6 +11,8 @@ public class AlarmPlatformConfig public class MqttConfig { + //public bool Local { get; set; } + public string Ip { get; set; } public int Port { get; set; } diff --git a/JiLinApp.Biz/TransmitAlarm/Entity/AlarmMessage.cs b/JiLinApp.Biz/TransmitAlarm/Entity/AlarmMessage.cs index 449aff4..dc32f16 100644 --- a/JiLinApp.Biz/TransmitAlarm/Entity/AlarmMessage.cs +++ b/JiLinApp.Biz/TransmitAlarm/Entity/AlarmMessage.cs @@ -4,7 +4,7 @@ public class AlarmMessage { /** (必填)传感器设备编码*/ public string LabelCode { get; set; } - public int ChannelId { get; set; } + public string ChannelId { get; set; } /** (必填)报警类型((1-视频报警,2-雷达报警;3-微振动警报,4-电子围网警报,9-其他报警))*/ public int WarnType { get; set; } /** (必填)报警级别(1-5)*/ diff --git a/JiLinApp.Biz/TransmitAlarm/Entity/AlarmMessageHelper.cs b/JiLinApp.Biz/TransmitAlarm/Entity/AlarmMessageHelper.cs index 56c6199..26ebaa1 100644 --- a/JiLinApp.Biz/TransmitAlarm/Entity/AlarmMessageHelper.cs +++ b/JiLinApp.Biz/TransmitAlarm/Entity/AlarmMessageHelper.cs @@ -12,7 +12,7 @@ public static class AlarmMessageHelper AlarmMessage obj = new() { LabelCode = Convert.ToString(msg.DeviceID), - ChannelId = Convert.ToInt32(msg.SensorAddr), + ChannelId = msg.SensorAddr, WarnType = 3, WarnLevel = code.Level, WarnContent = code.Content, @@ -29,7 +29,7 @@ public static class AlarmMessageHelper AlarmMessage obj = new() { LabelCode = Convert.ToString(msg.DeviceId), - ChannelId = msg.SectorId, + ChannelId = Convert.ToString(msg.SectorId), WarnType = 4, WarnLevel = code.Level, WarnContent = code.Content, diff --git a/JiLinApp.Biz/TransmitAlarm/Service/AlarmMqttService.cs b/JiLinApp.Biz/TransmitAlarm/Service/AlarmMqttService.cs index 1da84a6..609b5db 100644 --- a/JiLinApp.Biz/TransmitAlarm/Service/AlarmMqttService.cs +++ b/JiLinApp.Biz/TransmitAlarm/Service/AlarmMqttService.cs @@ -2,6 +2,8 @@ using MQTTnet; using MQTTnet.Client; using MQTTnet.Exceptions; +using MQTTnet.Protocol; +using MQTTnet.Server; using NewLife.Serialization; using Newtonsoft.Json.Linq; using System.Text; @@ -14,8 +16,12 @@ public class AlarmMqttService : IAlarmService private MqttConfig Config { get; } + //private MqttServer? Server { get; } + private IMqttClient Client { get; } + //private MqttServerOptions ServerOptions { get; } + private MqttClientOptions ClientOptions { get; } private MqttClientSubscribeOptions SubscribeOptions { get; } @@ -33,8 +39,7 @@ public class AlarmMqttService : IAlarmService public AlarmMqttService(MqttConfig config) { MqttFactory factory = new(); - IMqttClient client = factory.CreateMqttClient(); - client.ApplicationMessageReceivedAsync += Client_ApplicationMessageReceivedAsync; + ClientOptions = factory.CreateClientOptionsBuilder() .WithTcpServer(config.Ip, config.Port) .WithClientId(config.ClientId) @@ -46,6 +51,23 @@ public class AlarmMqttService : IAlarmService .WithTopicFilter(f => f.WithTopic(config.SubCmdTopic)) .Build(); + //if (config.Local) + //{ + // ServerOptions = factory.CreateServerOptionsBuilder() + // .WithDefaultEndpoint() + // .WithDefaultEndpointPort(config.Port) + // .Build(); + // MqttServer server = factory.CreateMqttServer(ServerOptions); + // server.ValidatingConnectionAsync += Server_ValidatingConnectionAsync; + // server.ClientConnectedAsync += Server_ClientConnectedAsync; + // server.ClientDisconnectedAsync += Server_ClientDisconnectedAsync; + // server.ClientAcknowledgedPublishPacketAsync += Server_ClientAcknowledgedPublishPacketAsync; + // Server = server; + //} + + IMqttClient client = factory.CreateMqttClient(); + client.ApplicationMessageReceivedAsync += Client_ApplicationMessageReceivedAsync; + Config = config; Client = client; } @@ -110,7 +132,38 @@ public class AlarmMqttService : IAlarmService #endregion Base - #region Receive + #region Server Event + + private Task Server_ValidatingConnectionAsync(ValidatingConnectionEventArgs arg) + { + if (arg.ClientId.Length == 0) arg.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid; + else if (arg.UserName != Config.UserName) arg.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword; + else if (arg.Password != Config.Password) arg.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword; + return Task.CompletedTask; + } + + private Task Server_ClientConnectedAsync(ClientConnectedEventArgs arg) + { + return Task.CompletedTask; + } + + private Task Server_ClientDisconnectedAsync(ClientDisconnectedEventArgs arg) + { + return Task.CompletedTask; + } + + private Task Server_ClientAcknowledgedPublishPacketAsync(ClientAcknowledgedPublishPacketEventArgs arg) + { + string clientId = arg.ClientId; + ushort packetIdentifier = arg.PublishPacket.PacketIdentifier; + string topic = arg.PublishPacket.Topic; + string msg = Encoding.UTF8.GetString(arg.PublishPacket.Payload); + return Task.CompletedTask; + } + + #endregion Server Event + + #region Client Event private Task Client_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg) { @@ -160,7 +213,7 @@ public class AlarmMqttService : IAlarmService } } - #endregion Receive + #endregion Client Event #region Send diff --git a/JiLinApp.Biz/TransmitAlarm/Service/AlarmZmqService.cs b/JiLinApp.Biz/TransmitAlarm/Service/AlarmZmqService.cs index c9ec46d..9932384 100644 --- a/JiLinApp.Biz/TransmitAlarm/Service/AlarmZmqService.cs +++ b/JiLinApp.Biz/TransmitAlarm/Service/AlarmZmqService.cs @@ -3,8 +3,11 @@ public class AlarmZmqService : IAlarmService { public event IAlarmService.HandleRecvEvent? OnFenceUdpSendDevices; + public event IAlarmService.HandleRecvEvent? OnVibrateTcpSendDevices; + public event IAlarmService.HandleRecvEvent? OnFenceUdpSendSensors; + public event IAlarmService.HandleRecvEvent? OnVibrateTcpSendSensors; public void Start() diff --git a/JiLinApp.Docking/Alarm/AlarmCodeHelper.cs b/JiLinApp.Docking/Alarm/AlarmCodeHelper.cs index 84d0a99..5a9ce1f 100644 --- a/JiLinApp.Docking/Alarm/AlarmCodeHelper.cs +++ b/JiLinApp.Docking/Alarm/AlarmCodeHelper.cs @@ -23,7 +23,8 @@ public class AlarmCodeHelper } public static void Init() - { } + { + } public static AlarmCode Get(string id) { diff --git a/JiLinApp.Docking/FenceAlarm/Service/UdpServer.cs b/JiLinApp.Docking/FenceAlarm/Service/UdpServer.cs index 0d14389..16da808 100644 --- a/JiLinApp.Docking/FenceAlarm/Service/UdpServer.cs +++ b/JiLinApp.Docking/FenceAlarm/Service/UdpServer.cs @@ -122,10 +122,12 @@ public class UdpServer return flag; } - public bool SendMessage(IPEndPoint ipep, byte[] byteMsg) + public bool SendMessage(IPEndPoint ipep, byte[] msg) { - int result = SendUdp.Send(byteMsg, byteMsg.Length, ipep); - return result >= byteMsg.Length; + int result = SendUdp.Send(msg, msg.Length, ipep); + bool flag = result >= msg.Length; + Console.WriteLine("Send to {0}:{1} => {2}, {3}", ipep.Address.ToString(), ipep.Port, DataMessage.ToHexString(msg), flag); + return flag; } #endregion Send diff --git a/JiLinApp.Docking/JiLinApp.Docking.csproj b/JiLinApp.Docking/JiLinApp.Docking.csproj index 5daedfc..e750c76 100644 --- a/JiLinApp.Docking/JiLinApp.Docking.csproj +++ b/JiLinApp.Docking/JiLinApp.Docking.csproj @@ -7,7 +7,9 @@ - + + + diff --git a/JiLinApp.Docking/Military/Config.cs b/JiLinApp.Docking/Military/Config.cs new file mode 100644 index 0000000..79c9ce6 --- /dev/null +++ b/JiLinApp.Docking/Military/Config.cs @@ -0,0 +1,14 @@ +namespace JiLinApp.Docking.Military; + +public class MilitaryConfig +{ + public string Url { get; set; } + + public string UserName { get; set; } + + public string Password { get; set; } + + public int RequestRetryTime { get; set; } + + public int RequestRetryInterval { get; set; } +} \ No newline at end of file diff --git a/JiLinApp.Docking/Military/Entity/CameraLinkageInfo.cs b/JiLinApp.Docking/Military/Entity/CameraLinkageInfo.cs new file mode 100644 index 0000000..a2d203f --- /dev/null +++ b/JiLinApp.Docking/Military/Entity/CameraLinkageInfo.cs @@ -0,0 +1,18 @@ +namespace JiLinApp.Docking.Military; + +public class CameraLinkageInfo +{ + #region Fields + + public string Id { get; set; } + + public string DeviceId { get; set; } + + public string SensorId { get; set; } + + public string CameraId { get; set; } + + public int[] PresetIds { get; set; } + + #endregion Fields +} \ No newline at end of file diff --git a/JiLinApp.Docking/Military/MilitaryService.cs b/JiLinApp.Docking/Military/MilitaryService.cs new file mode 100644 index 0000000..1b91066 --- /dev/null +++ b/JiLinApp.Docking/Military/MilitaryService.cs @@ -0,0 +1,158 @@ +using EC.Util.CameraSDK; +using EC.Util.Common; +using Flurl.Http; +using Newtonsoft.Json.Linq; + +namespace JiLinApp.Docking.Military; + +public class MilitaryService +{ + #region Fields + + private MilitaryConfig Config { get; } + + private string Token { get; set; } + + #endregion Fields + + public MilitaryService(MilitaryConfig config) + { + Config = config; + Token = Login(); + } + + #region Base + + private string GetUrl() + { + return Config.Url; + } + + #endregion Base + + #region Cmd + + public string Login() + { + string url = $"{GetUrl()}/sys/login"; + object data = new + { + username = Config.UserName, + password = Config.Password, + }; + JObject response = new(); + for (int i = 0; i < Config.RequestRetryTime; i++) + { + response = url.PostJsonAsync(data).ReceiveJson().Result; + bool success = response["success"].ToBoolean(); + if (!success) + { + Thread.Sleep(Config.RequestRetryInterval); + continue; + } + string? token = response["result"]?["token"]?.ToString(); + return token ?? string.Empty; + } + string? message = response["message"]?.ToString(); + throw new Exception(message); + } + + public List GetCameraList() + { + string url = $"{GetUrl()}/camera/setting/list"; + JObject response = new(); + for (int i = 0; i < Config.RequestRetryTime; i++) + { + response = url.GetAsync().ReceiveJson().Result; + bool success = response["success"].ToBoolean(); + if (!success) + { + Thread.Sleep(Config.RequestRetryInterval); + continue; + } + JToken records = response?["result"]?["records"] ?? new JObject(); + List list = new(); + foreach (var item in records) + { + CameraManufactor manufactor; + string factory = item?["factory_dictText"]?.ToString() ?? string.Empty; + if (factory.Contains("海康威视")) manufactor = CameraManufactor.HiK; + else if (factory.Contains("大华")) manufactor = CameraManufactor.DaHua; + else if (factory.Contains("宇视")) manufactor = CameraManufactor.YuShi; + else continue; + string id = item?["id"]?.ToString() ?? string.Empty; + string ip = item?["ip"]?.ToString() ?? string.Empty; + string username = item?["user"]?.ToString() ?? string.Empty; + string password = item?["password"]?.ToString() ?? string.Empty; + if (VerifyUtil.IsEmpty(id) || !VerifyUtil.IsIp(ip) || VerifyUtil.IsEmpty(username) || VerifyUtil.IsEmpty(password)) continue; + CameraInfo info = CameraInfo.New(manufactor, ip, username, password); + info.Id = id; + list.Add(info); + } + return list; + } + string? message = response["message"]?.ToString(); + throw new Exception(message); + } + + public List GetFencesInfoList() + { + string url = $"{GetUrl()}/msFencesInfo/list"; + JObject response = new(); + for (int i = 0; i < Config.RequestRetryTime; i++) + { + response = url.WithHeader("X-Access-Token", Token).GetAsync().ReceiveJson().Result; + bool success = response["success"].ToBoolean(); + if (!success) + { + Thread.Sleep(Config.RequestRetryInterval); + continue; + } + return new List(); + } + string? message = response["message"]?.ToString(); + throw new Exception(message); + } + + public List GetCameraLinkageList() + { + string url = $"{GetUrl()}/military/MsCameraLinkage/list"; + JObject response = new(); + for (int i = 0; i < Config.RequestRetryTime; i++) + { + response = url.GetAsync().ReceiveJson().Result; + bool success = response["success"].ToBoolean(); + if (!success) + { + Thread.Sleep(Config.RequestRetryInterval); + continue; + } + JToken records = response?["result"]?["records"] ?? new JObject(); + List list = new(); + foreach (var item in records) + { + string id = item?["id"]?.ToString() ?? string.Empty; + //string deviceId = item?["deviceId"]?.ToString() ?? string.Empty; + string deviceId = "0"; + string sensorId = item?["objCode"]?.ToString() ?? string.Empty; + string cameraId = item?["cameraId"]?.ToString() ?? string.Empty; + string placements = item?["placements"]?.ToString() ?? string.Empty; + int[] presetIds = Array.ConvertAll(placements.Split(","), int.Parse); + if (VerifyUtil.IsEmpty(id) || VerifyUtil.IsEmpty(sensorId) || VerifyUtil.IsEmpty(cameraId)) continue; + list.Add(new() + { + Id = id, + DeviceId = deviceId, + SensorId = sensorId, + CameraId = cameraId, + PresetIds = presetIds + }); + } + return list; + } + string? message = response["message"]?.ToString(); + throw new Exception(message); + } + + #endregion Cmd +} \ No newline at end of file diff --git a/JiLinApp.Docking/Ptz/PtzCmd.cs b/JiLinApp.Docking/Ptz/PtzCmd.cs index c4bf47d..937a030 100644 --- a/JiLinApp.Docking/Ptz/PtzCmd.cs +++ b/JiLinApp.Docking/Ptz/PtzCmd.cs @@ -140,7 +140,7 @@ public class PtzCameraCmd public static void PtzMove(ICameraSDK sdk, PtzCmdType cmdType, int[] args) { if (sdk == null || !sdk.ConnectSuccess() || args == null) return; - switch (sdk.CameraInfo.GetManufactor) + switch (sdk.CameraInfo.Manufactor) { case CameraManufactor.HiK: HikPtzMove(sdk, cmdType, args); diff --git a/JiLinApp.Docking/VibrateAlarm/Entity/ClientMessage.cs b/JiLinApp.Docking/VibrateAlarm/Entity/ClientMessage.cs index 69b6801..25584ee 100644 --- a/JiLinApp.Docking/VibrateAlarm/Entity/ClientMessage.cs +++ b/JiLinApp.Docking/VibrateAlarm/Entity/ClientMessage.cs @@ -16,7 +16,7 @@ public class ClientMessage get { if (Host != null) return Host.Ip; - if (Client != null) return Client.Client.RemoteEndPoint.ToString().Split(':')[0]; + //if (Client != null) return Client.Client.RemoteEndPoint.ToString().Split(':')[0]; return ""; } } @@ -26,7 +26,7 @@ public class ClientMessage get { if (Host != null) return Host.Port; - if (Client != null) return Client.Client.RemoteEndPoint.ToString().Split(':')[1]; + //if (Client != null) return Client.Client.RemoteEndPoint.ToString().Split(':')[1]; return "-1"; } } diff --git a/JiLinApp.Docking/VibrateAlarm/Service/AsyncTcpServer.cs b/JiLinApp.Docking/VibrateAlarm/Service/AsyncTcpServer.cs index 92490ba..ebe89fe 100644 --- a/JiLinApp.Docking/VibrateAlarm/Service/AsyncTcpServer.cs +++ b/JiLinApp.Docking/VibrateAlarm/Service/AsyncTcpServer.cs @@ -1,7 +1,6 @@ using System.Collections.Concurrent; using System.Net; using System.Net.Sockets; -using System.Runtime.InteropServices; using System.Text; namespace JiLinApp.Docking.VibrateAlarm; @@ -39,8 +38,6 @@ public class AsyncTcpServer : IDisposable #region Ctors - private byte[] InOptionValues { get; set; } - /// /// 异步TCP服务器 /// @@ -64,11 +61,6 @@ public class AsyncTcpServer : IDisposable /// 监听的端口 public AsyncTcpServer(IPAddress address, int port) { - uint dummy = 0; - InOptionValues = new byte[Marshal.SizeOf(dummy) * 3]; - BitConverter.GetBytes((uint)1).CopyTo(InOptionValues, 0); - BitConverter.GetBytes((uint)1000).CopyTo(InOptionValues, Marshal.SizeOf(dummy)); - BitConverter.GetBytes((uint)1000).CopyTo(InOptionValues, Marshal.SizeOf(dummy) * 2); Address = address; Port = port; Encoding = Encoding.Default; @@ -157,14 +149,18 @@ public class AsyncTcpServer : IDisposable /// public event EventHandler>? DatagramReceived; - private void RaiseClientConnected(TcpClient client) + private void RaiseClientConnected(string clientKey, TcpClientState clientState) { - ClientConnected?.Invoke(this, new TcpClientConnectedEventArgs(client)); + Clients.AddOrUpdate(clientKey, clientState, (n, o) => { return clientState; }); + ClientConnected?.Invoke(this, new TcpClientConnectedEventArgs(clientState.TcpClient)); } - private void RaiseClientDisconnected(TcpClient client) + private void RaiseClientDisconnected(string clientKey, TcpClient client) { - ClientDisconnected?.Invoke(this, new TcpClientDisconnectedEventArgs(client)); + if (Clients.TryRemove(clientKey, out _)) + { + ClientDisconnected?.Invoke(this, new TcpClientDisconnectedEventArgs(client)); + } } private void RaiseDatagramReceived(TcpClientState sender, byte[] datagram) @@ -181,11 +177,6 @@ public class AsyncTcpServer : IDisposable listener.BeginAcceptTcpClient(HandleTcpClientAccepted, listener); } - private void ReadBuffer(TcpClientState internalClient, NetworkStream networkStream) - { - networkStream.BeginRead(internalClient.Buffer, 0, internalClient.Buffer.Length, HandleDatagramReceived, internalClient); - } - private void HandleTcpClientAccepted(IAsyncResult ar) { if (!IsRunning()) return; @@ -195,7 +186,6 @@ public class AsyncTcpServer : IDisposable { listener = ar.AsyncState as TcpListener; client = listener?.EndAcceptTcpClient(ar); - client?.Client.IOControl(IOControlCode.KeepAliveValues, InOptionValues, null); } catch (Exception) { @@ -204,24 +194,22 @@ public class AsyncTcpServer : IDisposable if (listener == null || client == null || !client.Connected) return; byte[] buffer = new byte[client.ReceiveBufferSize]; - TcpClientState internalClient = new(client, buffer); + TcpClientState clientState = new(client, buffer); // add client connection to cache string clientKey = client.Client.RemoteEndPoint?.ToString() ?? ""; if (clientKey == "") return; - Clients.AddOrUpdate(clientKey, internalClient, (n, o) => { return internalClient; }); - RaiseClientConnected(client); + RaiseClientConnected(clientKey, clientState); // begin to read data try { - NetworkStream networkStream = internalClient.NetworkStream; - ReadBuffer(internalClient, networkStream); + NetworkStream networkStream = clientState.NetworkStream; + ReadBuffer(clientState, networkStream); } catch (Exception) { - Clients.TryRemove(clientKey, out _); - RaiseClientDisconnected(internalClient.TcpClient); + RaiseClientDisconnected(clientKey, clientState.TcpClient); return; } @@ -229,6 +217,11 @@ public class AsyncTcpServer : IDisposable AcceptTcpClient(listener); } + private void ReadBuffer(TcpClientState clientState, NetworkStream networkStream) + { + networkStream.BeginRead(clientState.Buffer, 0, clientState.Buffer.Length, HandleDatagramReceived, clientState); + } + private void HandleDatagramReceived(IAsyncResult ar) { if (!IsRunning()) return; @@ -239,8 +232,7 @@ public class AsyncTcpServer : IDisposable if (!internalClient.TcpClient.Connected) { // connection has been closed - Clients.TryRemove(clientKey, out _); - RaiseClientDisconnected(internalClient.TcpClient); + RaiseClientDisconnected(clientKey, internalClient.TcpClient); } NetworkStream networkStream; @@ -254,13 +246,13 @@ public class AsyncTcpServer : IDisposable } catch (Exception) { + RaiseClientDisconnected(clientKey, internalClient.TcpClient); return; } if (readBytesNum == 0) { // connection has been closed - Clients.TryRemove(clientKey, out _); - RaiseClientDisconnected(internalClient.TcpClient); + RaiseClientDisconnected(clientKey, internalClient.TcpClient); return; } @@ -280,15 +272,15 @@ public class AsyncTcpServer : IDisposable /// /// 发送报文至指定的客户端 /// - /// 客户端 + /// 客户端 /// 报文 - public void Send(TcpClient tcpClient, byte[] datagram) + public void Send(TcpClient client, byte[] datagram) { if (!IsRunning()) return; - if (tcpClient == null || !tcpClient.Connected || datagram == null) return; + if (client == null || !client.Connected || datagram == null) return; try { - NetworkStream stream = tcpClient.GetStream(); + NetworkStream stream = client.GetStream(); if (stream.CanWrite) { stream.Write(datagram, 0, datagram.Length); @@ -296,17 +288,20 @@ public class AsyncTcpServer : IDisposable } catch (Exception) { + string clientKey = client.Client.RemoteEndPoint?.ToString() ?? ""; + if (clientKey == "") return; + if (client != null) RaiseClientDisconnected(clientKey, client); } } /// /// 发送报文至指定的客户端 /// - /// 客户端 + /// 客户端 /// 报文 - public void Send(TcpClient tcpClient, string datagram) + public void Send(TcpClient client, string datagram) { - Send(tcpClient, Encoding.GetBytes(datagram)); + Send(client, Encoding.GetBytes(datagram)); } /// @@ -335,33 +330,36 @@ public class AsyncTcpServer : IDisposable /// /// 发送报文至指定的客户端 /// - /// 客户端 + /// 客户端 /// 报文 - public void SendAsync(TcpClient tcpClient, byte[] datagram) + public void SendAsync(TcpClient client, byte[] datagram) { if (!IsRunning()) return; - if (tcpClient == null || !tcpClient.Connected || datagram == null) return; + if (client == null || !client.Connected || datagram == null) return; try { - NetworkStream stream = tcpClient.GetStream(); + NetworkStream stream = client.GetStream(); if (stream.CanWrite) { - stream.BeginWrite(datagram, 0, datagram.Length, HandleDatagramWritten, tcpClient); + stream.BeginWrite(datagram, 0, datagram.Length, HandleDatagramWritten, client); } } catch (Exception) { + string clientKey = client.Client.RemoteEndPoint?.ToString() ?? ""; + if (clientKey == "") return; + if (client != null) RaiseClientDisconnected(clientKey, client); } } /// /// 发送报文至指定的客户端 /// - /// 客户端 + /// 客户端 /// 报文 - public void SendAsync(TcpClient tcpClient, string datagram) + public void SendAsync(TcpClient client, string datagram) { - SendAsync(tcpClient, Encoding.GetBytes(datagram)); + SendAsync(client, Encoding.GetBytes(datagram)); } /// @@ -389,12 +387,17 @@ public class AsyncTcpServer : IDisposable private void HandleDatagramWritten(IAsyncResult ar) { + TcpClient? client = null; try { - (ar.AsyncState as TcpClient)?.GetStream().EndWrite(ar); + client = ar.AsyncState as TcpClient; + client?.GetStream().EndWrite(ar); } catch (Exception) { + string clientKey = client?.Client.RemoteEndPoint?.ToString() ?? ""; + if (clientKey == "") return; + if (client != null) RaiseClientDisconnected(clientKey, client); } } diff --git a/JiLinApp.Docking/VibrateAlarm/Service/TcpManager.cs b/JiLinApp.Docking/VibrateAlarm/Service/TcpManager.cs index 36d484b..ba2cfe3 100644 --- a/JiLinApp.Docking/VibrateAlarm/Service/TcpManager.cs +++ b/JiLinApp.Docking/VibrateAlarm/Service/TcpManager.cs @@ -18,8 +18,6 @@ public class TcpManager private Timer HeartTimer { get; } = new(); - private Timer StateSpanTimer { get; } = new(); - #region Event public delegate void VibrateTcpDeviceStateEvent(ClientMessage device); @@ -476,8 +474,6 @@ public class TcpManager #region Set - private List Reqlist { get; } = new(); - private byte FrameNumber { get; set; } = 0; private DataMessage GetSendMessageHead(int deviceId, ClientMessage client, byte fun_num, byte datalen) @@ -485,7 +481,8 @@ public class TcpManager DataMessage msg = new() { DeviceId = deviceId, - SendIp = client.Client.Client.LocalEndPoint.ToString().Split(':')[0], + SendIp = client.Host.Ip, + //SendIp = client.Client.Client.LocalEndPoint.ToString().Split(':')[0], SendPort = Server.Port, ReceiveIp = client.Ip, ReceivePort = int.Parse(client.Port), diff --git a/JiLinApp.sln b/JiLinApp.sln index 30cace0..ab0c5ff 100644 --- a/JiLinApp.sln +++ b/JiLinApp.sln @@ -11,6 +11,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiLinApp.Docking", "JiLinAp EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JiLinApp.Biz", "JiLinApp.Biz\JiLinApp.Biz.csproj", "{7CE63A50-C92C-4554-8E0C-F7BED355C1FD}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{43972F12-0762-4EC2-AC09-900F53CC743D}" + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU diff --git a/JiLinApp/App.xaml.cs b/JiLinApp/App.xaml.cs index 1722163..a53ab48 100644 --- a/JiLinApp/App.xaml.cs +++ b/JiLinApp/App.xaml.cs @@ -1,4 +1,5 @@ -using JiLinApp.Core; +using EC.Util.Common; +using JiLinApp.Core; using JiLinApp.Pages.Main; using Prism.Ioc; using Prism.Modularity; diff --git a/JiLinApp/Components/CameraRealPlay.xaml b/JiLinApp/Components/CameraRealPlay.xaml index 888dba7..97af64f 100644 --- a/JiLinApp/Components/CameraRealPlay.xaml +++ b/JiLinApp/Components/CameraRealPlay.xaml @@ -29,6 +29,9 @@ + + + @@ -90,7 +93,7 @@ - + - + - + + + + + + + +