初始化版本

This commit is contained in:
LL
2025-11-14 16:12:32 +08:00
commit ea40f18aa6
326 changed files with 137063 additions and 0 deletions

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,81 @@
using System.Collections.Generic;
namespace NetWorkHelper.Addins
{
/// <summary>
/// 用于宿主应用程序向插件传递必要的参数信息
/// </summary>
public static class AddinUtil
{
private static IDictionary<string, object> DicUtil = new Dictionary<string, object>();
#region RegisterObject
/// <summary>
/// RegisterObject
/// </summary>
/// <param name="name"></param>
/// <param name="obj"></param>
public static void RegisterObject(string name, object obj)
{
lock (AddinUtil.DicUtil)
{
if (AddinUtil.DicUtil.ContainsKey(name))
{
AddinUtil.Remove(name);
}
AddinUtil.DicUtil.Add(name, obj);
}
}
#endregion
#region GetObject
/// <summary>
/// GetObject
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static object GetObject(string name)
{
lock (AddinUtil.DicUtil)
{
if (AddinUtil.DicUtil.ContainsKey(name))
{
return AddinUtil.DicUtil[name];
}
return null;
}
}
#endregion
#region Remove
/// <summary>
/// Remove
/// </summary>
/// <param name="name"></param>
public static void Remove(string name)
{
lock (AddinUtil.DicUtil)
{
if (AddinUtil.DicUtil.ContainsKey(name))
{
AddinUtil.DicUtil.Remove(name);
}
}
}
#endregion
#region Clear
/// <summary>
/// Clear
/// </summary>
public static void Clear()
{
lock (AddinUtil.DicUtil)
{
AddinUtil.DicUtil.Clear();
}
}
#endregion
}
}

View File

@@ -0,0 +1,49 @@

namespace NetWorkHelper.Addins
{
/// <summary>
/// 所有插件基本接口
/// </summary>
public interface IAddin
{
/// <summary>
/// OnLoading 生命周期回调当插件加载完毕被调用。可以从AddinUtil获取主应用传递的参数来初始化插件
/// </summary>
void OnLoading();
/// <summary>
/// BeforeTerminating 生命周期回调,卸载插件前调用
/// </summary>
void BeforeTerminating();
/// <summary>
/// Enabled 插件是否启用
/// </summary>
bool Enabled { get; set; }
/// <summary>
/// AddinKey 插件关键字不同的插件其Key是不一样的
/// </summary>
int AddinKey { get; }
/// <summary>
/// ServiceName 插件提供的服务的名字
/// </summary>
string AddinName { get; }
/// <summary>
/// Description 插件的描述信息
/// </summary>
string Description { get; }
/// <summary>
/// Version 插件版本
/// </summary>
float Version { get; }
}
public class AddinHelper
{
public const string AddinSign = "BinGoo.dll"; //所有的插件都以"BinGoo.dll"结尾
}
}

View File

@@ -0,0 +1,67 @@
using NetWorkHelper.ICommond;
using System.Collections.Generic;
namespace NetWorkHelper.Addins
{
/// <summary>
/// 用于加载/卸载,管理各种插件接口。
/// </summary>
public interface IAddinManager
{
#region Property
/// <summary>
/// CopyToMemory 是否将插件拷贝到内存后加载
/// </summary>
bool CopyToMemory { get; set; }
/// <summary>
/// AddinList 已加载的插件列表
/// </summary>
IList<IAddin> AddinList { get; } //集合中为IAddin
#endregion
#region Method
/// <summary>
/// LoadDefault 加载当前目录或子目录下的所有有效插件
/// </summary>
void LoadDefault();
/// <summary>
/// LoadAllAddins 加载指定目录下的所有插件
/// </summary>
void LoadAllAddins(string addinFolderPath, bool searchChildFolder);
/// <summary>
/// LoadAddinAssembly 加载指定的插件
/// </summary>
void LoadAddinAssembly(string assemblyPath);
/// <summary>
/// Clear 清空所有已经加载的插件
/// </summary>
void Clear();
/// <summary>
/// DynRemoveAddin 动态移除指定的插件
/// </summary>
void DynRemoveAddin(int addinKey);
/// <summary>
/// EnableAddin 启用指定的插件
/// </summary>
void EnableAddin(int addinKey);
/// <summary>
/// EnableAddin 禁用指定的插件
/// </summary>
void DisableAddin(int addinKey);
IAddin GetAddin(int addinKey);
#endregion
#region Event
event NetWorkEventHandler AddinsChanged;
#endregion
}
}

View File

@@ -0,0 +1,168 @@
using NetWorkHelper.Helper;
using NetWorkHelper.ICollections;
using NetWorkHelper.ICommond;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace NetWorkHelper.Addins
{
/// <summary>
/// 插件管理类
/// </summary>
public class NetAddinManagement : IAddinManager
{
private IDictionary<int, IAddin> dicAddins = new Dictionary<int, IAddin>();
public event NetWorkEventHandler AddinsChanged;
public NetAddinManagement()
{
this.AddinsChanged += delegate { };
}
#region IAddinManagement
#region LoadAllAddins
public void LoadAllAddins(string addin_FolderPath, bool searchChildFolder)
{
ReflectionHelper.TypeLoadConfig config = new ReflectionHelper.TypeLoadConfig(this.copyToMem, false, AddinHelper.AddinSign);
IList<Type> addinTypeList = ReflectionHelper.LoadDerivedType(typeof(IAddin), addin_FolderPath, searchChildFolder, config);
foreach (Type addinType in addinTypeList)
{
IAddin addin = (IAddin)Activator.CreateInstance(addinType);
this.dicAddins.Add(addin.AddinKey, addin);
addin.OnLoading();
}
this.AddinsChanged();
}
#endregion
#region LoadDefault
public void LoadDefault()
{
this.LoadAllAddins(AppDomain.CurrentDomain.BaseDirectory, true);
}
#endregion
#region LoadAddinAssembly
public void LoadAddinAssembly(string assemblyPath)
{
Assembly asm = null;
if (this.copyToMem)
{
byte[] addinStream = FileHelper.ReadFileReturnBytes(assemblyPath);
asm = Assembly.Load(addinStream);
}
else
{
asm = Assembly.LoadFrom(assemblyPath);
}
IList<IAddin> newList = ReflectionHelper.LoadDerivedInstance<IAddin>(asm);
foreach (IAddin newAddin in newList)
{
this.dicAddins.Add(newAddin.AddinKey, newAddin);
newAddin.OnLoading();
}
this.AddinsChanged();
}
#endregion
#region Clear ,DynRemoveAddin
public void Clear()
{
foreach (IAddin addin in this.dicAddins.Values)
{
try
{
addin.BeforeTerminating();
}
catch { }
}
this.dicAddins.Clear();
this.AddinsChanged();
}
public void DynRemoveAddin(int addinKey)
{
IAddin dest = this.GetAddin(addinKey);
if (dest != null)
{
dest.BeforeTerminating();
this.dicAddins.Remove(addinKey);
this.AddinsChanged();
}
}
private bool ContainsAddin(int addinKey)
{
return this.dicAddins.ContainsKey(addinKey);
}
#endregion
#region AddinList
public IList<IAddin> AddinList
{
get
{
return CollectionConverter.CopyAllToList<IAddin>(this.dicAddins.Values);
}
}
#endregion
#region GetAddin
public IAddin GetAddin(int addinKey)
{
if (!this.dicAddins.ContainsKey(addinKey))
{
return null;
}
return this.dicAddins[addinKey];
}
#endregion
#region event ,property
private bool copyToMem = false;
public bool CopyToMemory
{
get
{
return this.copyToMem;
}
set
{
this.copyToMem = value;
}
}
#endregion
#region EnableAddin ,DisableAddin
public void EnableAddin(int addinKey)
{
IAddin dest = this.GetAddin(addinKey);
if (dest != null)
{
dest.Enabled = true;
}
}
public void DisableAddin(int addinKey)
{
IAddin dest = this.GetAddin(addinKey);
if (dest != null)
{
dest.Enabled = false;
}
}
#endregion
#endregion
}
}

View File

@@ -0,0 +1,74 @@
/********************************************************************
* *
* * Copyright (C) 2013-2018 uiskin.cn
* * 作者: BinGoo QQ315567586
* * 请尊重作者劳动成果,请保留以上作者信息,禁止用于商业活动。
* *
* * 创建时间2014-08-05
* * 说明:应用程序帮助类
* *
********************************************************************/
using System.Diagnostics;
using System.Threading;
namespace NetWorkHelper.Helper
{
public static class ApplicationHelper
{
#region
/// <summary>
/// 启动一个应用程序或进程
/// </summary>
/// <param name="appFilePath">程序或线程的路径</param>
public static void StartApplication(string appFilePath)
{
Process downprocess = new Process();
downprocess.StartInfo.FileName = appFilePath;
downprocess.Start();
}
#endregion
#region
/// <summary>
/// 目标应用程序是否已经启动。通常用于判断单实例应用。将占用锁。
/// </summary>
/// <param name="instanceName">应用名称</param>
/// <returns></returns>
public static bool IsAppInstanceExist(string instanceName)
{
bool createdNew = false;
ApplicationHelper.MutexForSingletonExe = new Mutex(false, instanceName, out createdNew);
return (!createdNew);
}
public static System.Threading.Mutex MutexForSingletonExe = null;
/// <summary>
/// 释放进程中占用的程序。
/// </summary>
/// <param name="instanceName"></param>
public static void ReleaseAppInstance(string instanceName)
{
if (ApplicationHelper.MutexForSingletonExe != null)
{
ApplicationHelper.MutexForSingletonExe.Close();
ApplicationHelper.MutexForSingletonExe = null;
}
}
#endregion
#region
/// <summary>
/// 在浏览器中打开Url链接
/// </summary>
/// <param name="url"></param>
public static void OpenUrl(string url)
{
Process.Start(url);
}
#endregion
}
}

View File

@@ -0,0 +1,259 @@
using NetWorkHelper.ICollections;
using System;
using System.Collections.Generic;
namespace NetWorkHelper.Helper
{
public static class CollectionHelper
{
#region Find
/// <summary>
/// Find 从集合中选取符合条件的元素
/// </summary>
public static List<TObject> Find<TObject>(IEnumerable<TObject> source, Predicate<TObject> predicate)
{
List<TObject> list = new List<TObject>();
CollectionHelper.ActionOnSpecification(source, delegate (TObject ele) { list.Add(ele); }, predicate);
return list;
}
#endregion
#region FindFirstSpecification
/// <summary>
/// FindFirstSpecification 返回符合条件的第一个元素
/// </summary>
public static TObject FindFirstSpecification<TObject>(IEnumerable<TObject> source, Predicate<TObject> predicate)
{
foreach (TObject element in source)
{
if (predicate(element))
{
return element;
}
}
return default(TObject);
}
#endregion
#region ContainsSpecification
/// <summary>
/// ContainsSpecification 集合中是否包含满足predicate条件的元素。
/// </summary>
public static bool ContainsSpecification<TObject>(IEnumerable<TObject> source, Predicate<TObject> predicate, out TObject specification)
{
specification = default(TObject);
foreach (TObject element in source)
{
if (predicate(element))
{
specification = element;
return true;
}
}
return false;
}
/// <summary>
/// ContainsSpecification 集合中是否包含满足predicate条件的元素。
/// </summary>
public static bool ContainsSpecification<TObject>(IEnumerable<TObject> source, Predicate<TObject> predicate)
{
TObject specification;
return CollectionHelper.ContainsSpecification<TObject>(source, predicate, out specification);
}
#endregion
#region ActionOnSpecification
/// <summary>
/// ActionOnSpecification 对集合中满足predicate条件的元素执行action。如果没有条件predicate传入null。
/// </summary>
public static void ActionOnSpecification<TObject>(IEnumerable<TObject> collection, Action<TObject> action, Predicate<TObject> predicate)
{
if (collection == null)
{
return;
}
if (predicate == null)
{
foreach (TObject obj in collection)
{
action(obj);
}
return;
}
foreach (TObject obj in collection)
{
if (predicate(obj))
{
action(obj);
}
}
}
#endregion
#region ActionOnEach
/// <summary>
/// ActionOnEach 对集合中的每个元素执行action。
/// </summary>
public static void ActionOnEach<TObject>(IEnumerable<TObject> collection, Action<TObject> action)
{
CollectionHelper.ActionOnSpecification<TObject>(collection, action, null);
}
#endregion
#region GetPart
public static T[] GetPart<T>(T[] ary, int startIndex, int count)
{
return CollectionHelper.GetPart<T>(ary, startIndex, count, false);
}
public static T[] GetPart<T>(T[] ary, int startIndex, int count, bool reverse)
{
if (startIndex >= ary.Length)
{
return null;
}
if (ary.Length < startIndex + count)
{
count = ary.Length - startIndex;
}
T[] result = new T[count];
if (!reverse)
{
for (int i = 0; i < count; i++)
{
result[i] = ary[startIndex + i];
}
}
else
{
for (int i = 0; i < count; i++)
{
result[i] = ary[ary.Length - startIndex - 1 - i];
}
}
return result;
}
#endregion
#region BinarySearch
/// <summary>
/// BinarySearch 从已排序的列表中,采用二分查找找到目标在列表中的位置。
/// 如果刚好有个元素与目标相等则返回true且minIndex会被赋予该元素的位置否则返回false且minIndex会被赋予比目标小且最接近目标的元素的位置
/// </summary>
public static bool BinarySearch<T>(IList<T> sortedList, T target, out int minIndex) where T : IComparable
{
if (target.CompareTo(sortedList[0]) == 0)
{
minIndex = 0;
return true;
}
if (target.CompareTo(sortedList[0]) < 0)
{
minIndex = -1;
return false;
}
if (target.CompareTo(sortedList[sortedList.Count - 1]) == 0)
{
minIndex = sortedList.Count - 1;
return true;
}
if (target.CompareTo(sortedList[sortedList.Count - 1]) > 0)
{
minIndex = sortedList.Count - 1;
return false;
}
int targetPosIndex = -1;
int left = 0;
int right = sortedList.Count - 1;
while (right - left > 1)
{
int middle = (left + right) / 2;
if (target.CompareTo(sortedList[middle]) == 0)
{
minIndex = middle;
return true;
}
if (target.CompareTo(sortedList[middle]) < 0)
{
right = middle;
}
else
{
left = middle;
}
}
minIndex = left;
return false;
}
#endregion
#region GetIntersection GetUnion
/// <summary>
/// GetIntersection 高效地求两个List元素的交集。
/// </summary>
public static List<T> GetIntersection<T>(List<T> list1, List<T> list2) where T : IComparable
{
List<T> largList = list1.Count > list2.Count ? list1 : list2;
List<T> smallList = largList == list1 ? list2 : list1;
largList.Sort();
int minIndex = 0;
List<T> result = new List<T>();
foreach (T tmp in smallList)
{
if (CollectionHelper.BinarySearch<T>(largList, tmp, out minIndex))
{
result.Add(tmp);
}
}
return result;
}
/// <summary>
/// GetUnion 高效地求两个List元素的并集。
/// </summary>
public static List<T> GetUnion<T>(List<T> list1, List<T> list2)
{
SortedDictionary<T, int> result = new SortedDictionary<T, int>();
foreach (T tmp in list1)
{
if (!result.ContainsKey(tmp))
{
result.Add(tmp, 0);
}
}
foreach (T tmp in list2)
{
if (!result.ContainsKey(tmp))
{
result.Add(tmp, 0);
}
}
return (List<T>)CollectionConverter.CopyAllToList<T>(result.Keys);
}
#endregion
}
}

View File

@@ -0,0 +1,134 @@
using System;
using System.Text;
namespace NetWorkHelper.Helper
{
public class DataFrame
{
DataFrameHeader _header;
private byte[] _extend = new byte[0];
private byte[] _mask = new byte[0];
private byte[] _content = new byte[0];
public DataFrame(byte[] buffer)
{
//帧头
_header = new DataFrameHeader(buffer);
//扩展长度
if (_header.Length == 126)
{
_extend = new byte[2];
Buffer.BlockCopy(buffer, 2, _extend, 0, 2);
}
else if (_header.Length == 127)
{
_extend = new byte[8];
Buffer.BlockCopy(buffer, 2, _extend, 0, 8);
}
//是否有掩码
if (_header.HasMask)
{
_mask = new byte[4];
Buffer.BlockCopy(buffer, _extend.Length + 2, _mask, 0, 4);
}
//消息体
if (_extend.Length == 0)
{
_content = new byte[_header.Length];
Buffer.BlockCopy(buffer, _extend.Length + _mask.Length + 2, _content, 0, _content.Length);
}
else if (_extend.Length == 2)
{
int contentLength = (int)_extend[0] * 256 + (int)_extend[1];
_content = new byte[contentLength];
Buffer.BlockCopy(buffer, _extend.Length + _mask.Length + 2, _content, 0, contentLength > 1024 * 100 ? 1024 * 100 : contentLength);
}
else
{
long len = 0;
int n = 1;
for (int i = 7; i >= 0; i--)
{
len += (int)_extend[i] * n;
n *= 256;
}
_content = new byte[len];
Buffer.BlockCopy(buffer, _extend.Length + _mask.Length + 2, _content, 0, _content.Length);
}
if (_header.HasMask) _content = Mask(_content, _mask);
}
public DataFrame(string content)
{
_content = Encoding.UTF8.GetBytes(content);
int length = _content.Length;
if (length < 126)
{
_extend = new byte[0];
_header = new DataFrameHeader(true, false, false, false, 1, false, length);
}
else if (length < 65536)
{
_extend = new byte[2];
_header = new DataFrameHeader(true, false, false, false, 1, false, 126);
_extend[0] = (byte)(length / 256);
_extend[1] = (byte)(length % 256);
}
else
{
_extend = new byte[8];
_header = new DataFrameHeader(true, false, false, false, 1, false, 127);
int left = length;
int unit = 256;
for (int i = 7; i > 1; i--)
{
_extend[i] = (byte)(left % unit);
left = left / unit;
if (left == 0)
break;
}
}
}
public byte[] GetBytes()
{
byte[] buffer = new byte[2 + _extend.Length + _mask.Length + _content.Length];
Buffer.BlockCopy(_header.GetBytes(), 0, buffer, 0, 2);
Buffer.BlockCopy(_extend, 0, buffer, 2, _extend.Length);
Buffer.BlockCopy(_mask, 0, buffer, 2 + _extend.Length, _mask.Length);
Buffer.BlockCopy(_content, 0, buffer, 2 + _extend.Length + _mask.Length, _content.Length);
return buffer;
}
public string Text
{
get
{
if (_header.OpCode != 1)
return string.Empty;
return Encoding.UTF8.GetString(_content);
}
}
private byte[] Mask(byte[] data, byte[] mask)
{
for (var i = 0; i < data.Length; i++)
{
data[i] = (byte)(data[i] ^ mask[i % 4]);
}
return data;
}
}
}

View File

@@ -0,0 +1,80 @@
using System;
namespace NetWorkHelper.Helper
{
public class DataFrameHeader
{
private bool _fin;
private bool _rsv1;
private bool _rsv2;
private bool _rsv3;
private sbyte _opcode;
private bool _maskcode;
private sbyte _payloadlength;
public bool FIN { get { return _fin; } }
public bool RSV1 { get { return _rsv1; } }
public bool RSV2 { get { return _rsv2; } }
public bool RSV3 { get { return _rsv3; } }
public sbyte OpCode { get { return _opcode; } }
public bool HasMask { get { return _maskcode; } }
public sbyte Length { get { return _payloadlength; } }
public DataFrameHeader(byte[] buffer)
{
if (buffer.Length < 2)
throw new Exception("无效的数据头.");
//第一个字节
_fin = (buffer[0] & 0x80) == 0x80;
_rsv1 = (buffer[0] & 0x40) == 0x40;
_rsv2 = (buffer[0] & 0x20) == 0x20;
_rsv3 = (buffer[0] & 0x10) == 0x10;
_opcode = (sbyte)(buffer[0] & 0x0f);
//第二个字节
_maskcode = (buffer[1] & 0x80) == 0x80;
_payloadlength = (sbyte)(buffer[1] & 0x7f);
}
//发送封装数据
public DataFrameHeader(bool fin, bool rsv1, bool rsv2, bool rsv3, sbyte opcode, bool hasmask, int length)
{
_fin = fin;
_rsv1 = rsv1;
_rsv2 = rsv2;
_rsv3 = rsv3;
_opcode = opcode;
//第二个字节
_maskcode = hasmask;
_payloadlength = (sbyte)length;
}
//返回帧头字节
public byte[] GetBytes()
{
byte[] buffer = { 0, 0 };
if (_fin) buffer[0] ^= 0x80;
if (_rsv1) buffer[0] ^= 0x40;
if (_rsv2) buffer[0] ^= 0x20;
if (_rsv3) buffer[0] ^= 0x10;
buffer[0] ^= (byte)_opcode;
if (_maskcode) buffer[1] ^= 0x80;
buffer[1] ^= (byte)_payloadlength;
return buffer;
}
}
}

View File

@@ -0,0 +1,571 @@
/********************************************************************
* *
* * Copyright (C) 2013-2018 uiskin.cn
* * 作者: BinGoo QQ315567586
* * 请尊重作者劳动成果,请保留以上作者信息,禁止用于商业活动。
* *
* * 创建时间2014-08-05
* * 说明:文件操作类
* *
********************************************************************/
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace NetWorkHelper.Helper
{
public static class FileHelper
{
#region
/// <summary>
/// 将字符串写成文件
/// </summary>
public static void GenerateFile(string filePath, string text)
{
string directoryPath = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.Write(text);
sw.Flush();
sw.Close();
fs.Close();
}
#endregion
#region
/// <summary>
/// 读取文本文件的内容
/// </summary>
public static string GetFileContent(string file_path)
{
if (!File.Exists(file_path))
{
return null;
}
StreamReader reader = new StreamReader(file_path, Encoding.UTF8);
string content = reader.ReadToEnd();
reader.Close();
return content;
}
#endregion
#region
/// <summary>
/// 将二进制数据写入文件中
/// </summary>
public static void WriteBuffToFile(byte[] buff, int offset, int len, string filePath)
{
string directoryPath = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buff, offset, len);
bw.Flush();
bw.Close();
fs.Close();
}
/// <summary>
/// WriteBuffToFile 将二进制数据写入文件中
/// </summary>
public static void WriteBuffToFile(byte[] buff, string filePath)
{
string directoryPath = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buff);
bw.Flush();
bw.Close();
fs.Close();
}
#endregion
#region
/// <summary>
/// 从文件中读取二进制数据
/// </summary>
public static byte[] ReadFileReturnBytes(string filePath)
{
if (!File.Exists(filePath))
{
return null;
}
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryReader br = new BinaryReader(fs);
byte[] buff = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
return buff;
}
#endregion
#region
/// <summary>
/// 获取要打开的文件路径
/// </summary>
public static string GetFileToOpen(string title)
{
OpenFileDialog openDlg = new OpenFileDialog();
openDlg.Filter = "All Files (*.*)|*.*";
openDlg.FileName = "";
if (title != null)
{
openDlg.Title = title;
}
openDlg.CheckFileExists = true;
openDlg.CheckPathExists = true;
DialogResult res = openDlg.ShowDialog();
if (res == DialogResult.OK)
{
return openDlg.FileName;
}
return null;
}
/// <summary>
/// 获取要打开的文件路径
/// </summary>
/// <param name="title">对话框标题</param>
/// <param name="iniDir">初始目录</param>
/// <param name="extendName">文件类型</param>
/// <returns></returns>
public static string GetFileToOpen(string title, string iniDir, string extendName)
{
return GetFileToOpen2(title, iniDir, extendName);
}
/// <summary>
/// 获取要打开的文件路径
/// </summary>
/// <param name="title">对话框标题</param>
/// <param name="iniDir">初始目录</param>
/// <param name="extendNames">文件类型</param>
/// <returns></returns>
public static string GetFileToOpen2(string title, string iniDir, params string[] extendNames)
{
StringBuilder filterBuilder = new StringBuilder("(");
for (int i = 0; i < extendNames.Length; i++)
{
filterBuilder.Append("*");
filterBuilder.Append(extendNames[i]);
if (i < extendNames.Length - 1)
{
filterBuilder.Append(";");
}
else
{
filterBuilder.Append(")");
}
}
filterBuilder.Append("|");
for (int i = 0; i < extendNames.Length; i++)
{
filterBuilder.Append("*");
filterBuilder.Append(extendNames[i]);
if (i < extendNames.Length - 1)
{
filterBuilder.Append(";");
}
}
OpenFileDialog openDlg = new OpenFileDialog();
openDlg.Filter = filterBuilder.ToString();
openDlg.FileName = "";
openDlg.InitialDirectory = iniDir;
if (title != null)
{
openDlg.Title = title;
}
openDlg.CheckFileExists = true;
openDlg.CheckPathExists = true;
DialogResult res = openDlg.ShowDialog();
if (res == DialogResult.OK)
{
return openDlg.FileName;
}
return null;
}
#endregion
#region
/// <summary>
/// 获取要打开的文件夹
/// </summary>
/// <param name="newFolderButton">新建文件夹按钮是否显示在浏览文件夹对话框中</param>
/// <returns></returns>
public static string GetFolderToOpen(bool newFolderButton)
{
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.ShowNewFolderButton = newFolderButton;
DialogResult res = folderDialog.ShowDialog();
if (res == DialogResult.OK)
{
return folderDialog.SelectedPath;
}
return null;
}
#endregion
#region
/// <summary>
/// 获取要保存的文件的路径
/// </summary>
/// <param name="title">对话框标题</param>
/// <param name="defaultName">默认名称</param>
/// <param name="iniDir">初始化文件夹</param>
/// <returns></returns>
public static string GetPathToSave(string title, string defaultName, string iniDir)
{
string extendName = Path.GetExtension(defaultName);
SaveFileDialog saveDlg = new SaveFileDialog();
saveDlg.Filter = string.Format("The Files (*{0})|*{0}", extendName);
saveDlg.FileName = defaultName;
saveDlg.InitialDirectory = iniDir;
saveDlg.OverwritePrompt = false;
if (title != null)
{
saveDlg.Title = title;
}
DialogResult res = saveDlg.ShowDialog();
if (res == DialogResult.OK)
{
return saveDlg.FileName;
}
return null;
}
#endregion
#region
/// <summary>
/// 获取不包括路径的文件名
/// </summary>
/// <param name="filePath">指定的文件夹</param>
/// <returns></returns>
public static string GetFileNameNoPath(string filePath)
{
return Path.GetFileName(filePath);
}
#endregion
#region
/// <summary>
/// 获取目标文件的大小
/// </summary>
/// <param name="filePath">文件路径</param>
/// <returns></returns>
public static ulong GetFileSize(string filePath)
{
FileInfo info = new FileInfo(filePath);
return (ulong)info.Length;
}
#endregion
#region
/// <summary>
/// 获取某个文件夹的大小。
/// </summary>
/// <param name="dirPath">文件夹路径</param>
/// <returns></returns>
public static ulong GetDirectorySize(string dirPath)
{
if (!Directory.Exists(dirPath))
{
return 0;
}
ulong len = 0;
DirectoryInfo di = new DirectoryInfo(dirPath);
foreach (FileInfo fi in di.GetFiles())
{
len += (ulong)fi.Length;
}
DirectoryInfo[] dis = di.GetDirectories();
if (dis.Length > 0)
{
for (int i = 0; i < dis.Length; i++)
{
len += FileHelper.GetDirectorySize(dis[i].FullName);
}
}
return len;
}
#endregion
#region
/// <summary>
/// 从文件流中读取指定大小的内容
/// </summary>
/// <param name="fs"></param>
/// <param name="buff"></param>
/// <param name="count"></param>
/// <param name="offset"></param>
public static void ReadFileData(FileStream fs, byte[] buff, int count, int offset)
{
int readCount = 0;
while (readCount < count)
{
int read = fs.Read(buff, offset + readCount, count - readCount);
readCount += read;
}
return;
}
#endregion
#region
/// <summary>
/// 获取文件所在的目录路径
/// </summary>
/// <param name="filePath">文件路径</param>
/// <returns></returns>
public static string GetFileDirectory(string filePath)
{
return Path.GetDirectoryName(filePath);
}
#endregion
#region
/// <summary>
/// 删除文件
/// </summary>
/// <param name="filePath">文件路径</param>
public static void DeleteFile(string filePath)
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
#endregion
#region
/// <summary>
/// 确保扩展名正确
/// </summary>
/// <param name="origin_path">文件名</param>
/// <param name="extend_name">扩展名</param>
/// <returns></returns>
public static string EnsureExtendName(string origin_path, string extend_name)
{
if (Path.GetExtension(origin_path) != extend_name)
{
origin_path += extend_name;
}
return origin_path;
}
#endregion
#region
/// <summary>
/// 创建文件夹
/// </summary>
/// <param name="dirPath">文件夹路径</param>
public static void ClearDirectory(string dirPath)
{
string[] filePaths = Directory.GetFiles(dirPath);
foreach (string file in filePaths)
{
File.Delete(file);
}
foreach (string childDirPath in Directory.GetDirectories(dirPath))
{
FileHelper.DeleteDirectory(childDirPath);
}
}
#endregion
#region
/// <summary>
/// 删除文件夹
/// </summary>
/// <param name="dirPath">文件夹路径</param>
public static void DeleteDirectory(string dirPath)
{
foreach (string filePath in Directory.GetFiles(dirPath))
{
File.Delete(filePath);
}
foreach (string childDirPath in Directory.GetDirectories(dirPath))
{
FileHelper.DeleteDirectory(childDirPath);
}
DirectoryInfo dir = new DirectoryInfo(dirPath);
dir.Refresh();
if ((dir.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
dir.Attributes &= ~FileAttributes.ReadOnly;
}
dir.Delete();
}
#endregion
#region
/// <summary>
/// 将某个文件夹下的多个文件和子文件夹移到另外一个目录中。
/// </summary>
/// <param name="oldParentDirectoryPath">移动之前文件和子文件夹所处的父目录路径</param>
/// <param name="filesBeMoved">被移动的文件名称的集合</param>
/// <param name="directoriesBeMoved">被移动的文件夹名称的集合</param>
/// <param name="newParentDirectoryPath">移往的目标文件夹路径</param>
public static void Move(string oldParentDirectoryPath, IEnumerable<string> filesBeMoved, IEnumerable<string> directoriesBeMoved, string newParentDirectoryPath)
{
if (filesBeMoved != null)
{
foreach (string beMoved in filesBeMoved)
{
string pathOfBeMoved = oldParentDirectoryPath + beMoved;
if (File.Exists(pathOfBeMoved))
{
File.Move(pathOfBeMoved, newParentDirectoryPath + beMoved);
}
}
}
if (directoriesBeMoved != null)
{
foreach (string beMoved in directoriesBeMoved)
{
string pathOfBeMoved = oldParentDirectoryPath + beMoved;
if (Directory.Exists(pathOfBeMoved))
{
Directory.Move(pathOfBeMoved, newParentDirectoryPath + beMoved);
}
}
}
}
#endregion
#region
/// <summary>
/// 拷贝多个文件和文件夹
/// </summary>
/// <param name="sourceParentDirectoryPath">被拷贝的文件和文件夹所处的父目录路径</param>
/// <param name="filesBeCopyed">被复制的文件名称的集合</param>
/// <param name="directoriesCopyed">被复制的文件夹名称的集合</param>
/// <param name="destParentDirectoryPath">目标目录的路径</param>
public static void Copy(string sourceParentDirectoryPath, IEnumerable<string> filesBeCopyed, IEnumerable<string> directoriesCopyed, string destParentDirectoryPath)
{
bool sameParentDir = sourceParentDirectoryPath == destParentDirectoryPath;
if (filesBeCopyed != null)
{
foreach (string beCopyed in filesBeCopyed)
{
string newName = beCopyed;
while (sameParentDir && File.Exists(destParentDirectoryPath + newName))
{
newName = "副本-" + newName;
}
string pathOfBeCopyed = sourceParentDirectoryPath + beCopyed;
if (File.Exists(pathOfBeCopyed))
{
File.Copy(pathOfBeCopyed, destParentDirectoryPath + newName);
}
}
}
if (directoriesCopyed != null)
{
foreach (string beCopyed in directoriesCopyed)
{
string newName = beCopyed;
while (sameParentDir && Directory.Exists(destParentDirectoryPath + newName))
{
newName = "副本-" + newName;
}
string pathOfBeCopyed = sourceParentDirectoryPath + beCopyed;
if (Directory.Exists(pathOfBeCopyed))
{
CopyDirectoryAndFiles(sourceParentDirectoryPath, beCopyed, destParentDirectoryPath, newName);
}
}
}
}
/// <summary>
/// 递归拷贝文件夹以及下面的所有文件
/// </summary>
private static void CopyDirectoryAndFiles(string sourceParentDirectoryPath, string dirBeCopyed, string destParentDirectoryPath, string newDirName)
{
Directory.CreateDirectory(destParentDirectoryPath + newDirName);
DirectoryInfo source = new DirectoryInfo(sourceParentDirectoryPath + dirBeCopyed);
foreach (FileInfo file in source.GetFiles())
{
File.Copy(file.FullName, destParentDirectoryPath + newDirName + "\\" + file.Name);
}
foreach (DirectoryInfo dir in source.GetDirectories())
{
CopyDirectoryAndFiles(sourceParentDirectoryPath + dirBeCopyed + "\\", dir.Name, destParentDirectoryPath + newDirName + "\\", dir.Name);
}
}
#endregion
#region
/// <summary>
/// 获取目标目录下以及其子目录下的所有文件(采用相对路径)
/// </summary>
public static List<string> GetOffspringFiles(string dirPath)
{
List<string> list = new List<string>();
DirectoryInfo dir = new DirectoryInfo(dirPath);
DoGetOffspringFiles(dirPath, dir, ref list);
return list;
}
private static void DoGetOffspringFiles(string rootPath, DirectoryInfo dir, ref List<string> list)
{
foreach (FileInfo file in dir.GetFiles())
{
list.Add(file.FullName.Substring(rootPath.Length));
}
foreach (DirectoryInfo childDir in dir.GetDirectories())
{
DoGetOffspringFiles(rootPath, childDir, ref list);
}
}
#endregion
}
}

View File

@@ -0,0 +1,97 @@
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace NetWorkHelper
{
public static class ImageHelper
{
/// <summary>
/// Convert Image to Byte[]
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public static byte[] ImageToBytes(Image image)
{
ImageFormat format = image.RawFormat;
using (MemoryStream ms = new MemoryStream())
{
if (format.Equals(ImageFormat.Jpeg))
{
image.Save(ms, ImageFormat.Jpeg);
}
else if (format.Equals(ImageFormat.Png))
{
image.Save(ms, ImageFormat.Png);
}
else if (format.Equals(ImageFormat.Bmp))
{
image.Save(ms, ImageFormat.Bmp);
}
else if (format.Equals(ImageFormat.Gif))
{
image.Save(ms, ImageFormat.Gif);
}
else if (format.Equals(ImageFormat.Icon))
{
image.Save(ms, ImageFormat.Icon);
}
byte[] buffer = new byte[ms.Length];
//Image.Save()会改变MemoryStream的Position需要重新Seek到Begin
ms.Seek(0, SeekOrigin.Begin);
ms.Read(buffer, 0, buffer.Length);
return buffer;
}
}
/// <summary>
/// Convert Byte[] to Image
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static Image BytesToImage(byte[] buffer)
{
MemoryStream ms = new MemoryStream(buffer);
Image image = System.Drawing.Image.FromStream(ms);
return image;
}
/// <summary>
/// Convert Byte[] to a picture and Store it in file
/// </summary>
/// <param name="fileName"></param>
/// <param name="buffer"></param>
/// <returns></returns>
public static string CreateImageFromBytes(string fileName, byte[] buffer)
{
string file = fileName;
Image image = BytesToImage(buffer);
ImageFormat format = image.RawFormat;
if (format.Equals(ImageFormat.Jpeg))
{
file += ".jpeg";
}
else if (format.Equals(ImageFormat.Png))
{
file += ".png";
}
else if (format.Equals(ImageFormat.Bmp))
{
file += ".bmp";
}
else if (format.Equals(ImageFormat.Gif))
{
file += ".gif";
}
else if (format.Equals(ImageFormat.Icon))
{
file += ".icon";
}
System.IO.FileInfo info = new System.IO.FileInfo(file);
System.IO.Directory.CreateDirectory(info.Directory.FullName);
File.WriteAllBytes(file, buffer);
return file;
}
}
}

View File

@@ -0,0 +1,57 @@
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace NetWorkHelper
{
public static class MD5Helper
{
public static string CretaeMD5(string fileName)
{
string hashStr = string.Empty;
try
{
FileStream fs = new FileStream(
fileName,
FileMode.Open,
FileAccess.Read,
FileShare.Read);
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] hash = md5.ComputeHash(fs);
hashStr = ByteArrayToHexString(hash);
fs.Close();
fs.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return hashStr;
}
public static string CretaeMD5(Stream stream)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] hash = md5.ComputeHash(stream);
return ByteArrayToHexString(hash);
}
public static string CretaeMD5(byte[] buffer, int offset, int count)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] hash = md5.ComputeHash(buffer, offset, count);
return ByteArrayToHexString(hash);
}
private static string ByteArrayToHexString(byte[] values)
{
StringBuilder sb = new StringBuilder();
foreach (byte value in values)
{
sb.AppendFormat("{0:X2}", value);
}
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,582 @@
using NetWorkHelper.IBase;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace NetWorkHelper.Helper
{
public static class ReflectionHelper
{
#region
/// <summary>
/// GetType 通过完全限定的类型名来加载对应的类型。typeAndAssName如"NetWorkHelper.Filters.SourceFilter,NetWorkHelper"。
/// 如果为系统简单类型,则可以不带程序集名称。
/// </summary>
public static Type GetType(string typeAndAssName)
{
string[] names = typeAndAssName.Split(',');
if (names.Length < 2)
{
return Type.GetType(typeAndAssName);
}
return ReflectionHelper.GetType(names[0].Trim(), names[1].Trim());
}
/// <summary>
/// GetType 加载assemblyName程序集中的名为typeFullName的类型。assemblyName不用带扩展名如果目标类型在当前程序集中assemblyName传入null
/// </summary>
public static Type GetType(string typeFullName, string assemblyName)
{
if (assemblyName == null)
{
return Type.GetType(typeFullName);
}
//搜索当前域中已加载的程序集
Assembly[] asses = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly ass in asses)
{
string[] names = ass.FullName.Split(',');
if (names[0].Trim() == assemblyName.Trim())
{
return ass.GetType(typeFullName);
}
}
//加载目标程序集
Assembly tarAssem = Assembly.Load(assemblyName);
if (tarAssem != null)
{
return tarAssem.GetType(typeFullName);
}
return null;
}
#endregion
#region GetTypeFullName
public static string GetTypeFullName(Type t)
{
return t.FullName + "," + t.Assembly.FullName.Split(',')[0];
}
#endregion
#region LoadDerivedInstance
/// <summary>
/// LoadDerivedInstance 将程序集中所有继承自TBase的类型实例化
/// </summary>
/// <typeparam name="TBase">基础类型(或接口类型)</typeparam>
/// <param name="asm">目标程序集</param>
/// <returns>TBase实例列表</returns>
public static IList<TBase> LoadDerivedInstance<TBase>(Assembly asm)
{
IList<TBase> list = new List<TBase>();
Type supType = typeof(TBase);
foreach (Type t in asm.GetTypes())
{
if (supType.IsAssignableFrom(t) && (!t.IsAbstract) && (!t.IsInterface))
{
TBase instance = (TBase)Activator.CreateInstance(t);
list.Add(instance);
}
}
return list;
}
#endregion
#region LoadDerivedType
/// <summary>
/// LoadDerivedType 加载directorySearched目录下所有程序集中的所有派生自baseType的类型
/// </summary>
/// <typeparam name="baseType">基类(或接口)类型</typeparam>
/// <param name="directorySearched">搜索的目录</param>
/// <param name="searchChildFolder">是否搜索子目录中的程序集</param>
/// <param name="config">高级配置可以传入null采用默认配置</param>
/// <returns>所有从BaseType派生的类型列表</returns>
public static IList<Type> LoadDerivedType(Type baseType, string directorySearched, bool searchChildFolder, TypeLoadConfig config)
{
if (config == null)
{
config = new TypeLoadConfig();
}
IList<Type> derivedTypeList = new List<Type>();
if (searchChildFolder)
{
ReflectionHelper.LoadDerivedTypeInAllFolder(baseType, derivedTypeList, directorySearched, config);
}
else
{
ReflectionHelper.LoadDerivedTypeInOneFolder(baseType, derivedTypeList, directorySearched, config);
}
return derivedTypeList;
}
#region TypeLoadConfig
public class TypeLoadConfig
{
#region Ctor
public TypeLoadConfig() { }
public TypeLoadConfig(bool copyToMem, bool loadAbstract, string postfix)
{
this.copyToMemory = copyToMem;
this.loadAbstractType = loadAbstract;
this.targetFilePostfix = postfix;
}
#endregion
#region CopyToMemory
private bool copyToMemory = false;
/// <summary>
/// CopyToMem 是否将程序集拷贝到内存后加载
/// </summary>
public bool CopyToMemory
{
get { return copyToMemory; }
set { copyToMemory = value; }
}
#endregion
#region LoadAbstractType
private bool loadAbstractType = false;
/// <summary>
/// LoadAbstractType 是否加载抽象类型
/// </summary>
public bool LoadAbstractType
{
get { return loadAbstractType; }
set { loadAbstractType = value; }
}
#endregion
#region TargetFilePostfix
private string targetFilePostfix = ".dll";
/// <summary>
/// TargetFilePostfix 搜索的目标程序集的后缀名
/// </summary>
public string TargetFilePostfix
{
get { return targetFilePostfix; }
set { targetFilePostfix = value; }
}
#endregion
}
#endregion
#region LoadDerivedTypeInAllFolder
private static void LoadDerivedTypeInAllFolder(Type baseType, IList<Type> derivedTypeList, string folderPath, TypeLoadConfig config)
{
ReflectionHelper.LoadDerivedTypeInOneFolder(baseType, derivedTypeList, folderPath, config);
string[] folders = Directory.GetDirectories(folderPath);
if (folders != null)
{
foreach (string nextFolder in folders)
{
ReflectionHelper.LoadDerivedTypeInAllFolder(baseType, derivedTypeList, nextFolder, config);
}
}
}
#endregion
#region LoadDerivedTypeInOneFolder
private static void LoadDerivedTypeInOneFolder(Type baseType, IList<Type> derivedTypeList, string folderPath, TypeLoadConfig config)
{
string[] files = Directory.GetFiles(folderPath);
foreach (string file in files)
{
if (config.TargetFilePostfix != null)
{
if (!file.EndsWith(config.TargetFilePostfix))
{
continue;
}
}
Assembly asm = null;
#region Asm
try
{
if (config.CopyToMemory)
{
byte[] addinStream = FileHelper.ReadFileReturnBytes(file);
asm = Assembly.Load(addinStream);
}
else
{
asm = Assembly.LoadFrom(file);
}
}
catch (Exception ee)
{
ee = ee;
}
if (asm == null)
{
continue;
}
#endregion
Type[] types = asm.GetTypes();
foreach (Type t in types)
{
if (t.IsSubclassOf(baseType) || baseType.IsAssignableFrom(t))
{
bool canLoad = config.LoadAbstractType ? true : (!t.IsAbstract);
if (canLoad)
{
derivedTypeList.Add(t);
}
}
}
}
}
#endregion
#endregion
#region SetProperty
/// <summary>
/// SetProperty 如果list中的object具有指定的propertyName属性则设置该属性的值为proValue
/// </summary>
public static void SetProperty(IList<object> objs, string propertyName, object proValue)
{
object[] args = { proValue };
foreach (object target in objs)
{
ReflectionHelper.SetProperty(target, propertyName, proValue);
}
}
public static void SetProperty(object obj, string propertyName, object proValue)
{
ReflectionHelper.SetProperty(obj, propertyName, proValue, true);
}
/// <summary>
/// SetProperty 如果object具有指定的propertyName属性则设置该属性的值为proValue
/// </summary>
public static void SetProperty(object obj, string propertyName, object proValue, bool ignoreError)
{
Type t = obj.GetType();
PropertyInfo pro = t.GetProperty(propertyName);
if ((pro == null) || (!pro.CanWrite))
{
if (!ignoreError)
{
string msg = string.Format("The setter of property named '{0}' not found in '{1}'.", propertyName, t);
throw new Exception(msg);
}
return;
}
#region
try
{
proValue = TypeHelper.ChangeType(pro.PropertyType, proValue);
}
catch { }
#endregion
object[] args = { proValue };
t.InvokeMember(propertyName, BindingFlags.Public | BindingFlags.IgnoreCase |
BindingFlags.Instance | BindingFlags.SetProperty, null, obj, args);
}
#endregion
#region GetProperty
/// <summary>
/// GetProperty 根据指定的属性名获取目标对象该属性的值
/// </summary>
public static object GetProperty(object obj, string propertyName)
{
Type t = obj.GetType();
return t.InvokeMember(propertyName, BindingFlags.Default | BindingFlags.GetProperty, null, obj, null);
}
#endregion
#region GetFieldValue
/// <summary>
/// GetFieldValue 取得目标对象的指定field的值field可以是private
/// </summary>
public static object GetFieldValue(object obj, string fieldName)
{
Type t = obj.GetType();
FieldInfo field = t.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
if (field == null)
{
string msg = string.Format("The field named '{0}' not found in '{1}'.", fieldName, t);
throw new Exception(msg);
}
return field.GetValue(obj);
}
#endregion
#region SetFieldValue
/// <summary>
/// SetFieldValue 设置目标对象的指定field的值field可以是private
/// </summary>
public static void SetFieldValue(object obj, string fieldName, object val)
{
Type t = obj.GetType();
FieldInfo field = t.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetField | BindingFlags.Instance);
if (field == null)
{
string msg = string.Format("The field named '{0}' not found in '{1}'.", fieldName, t);
throw new Exception(msg);
}
field.SetValue(obj, val);
}
#endregion
#region CopyProperty
/// <summary>
/// CopyProperty 将source中的属性的值赋给target上同名的属性
/// 使用CopyProperty可以方便的实现拷贝构造函数
/// </summary>
public static void CopyProperty(object source, object target)
{
ReflectionHelper.CopyProperty(source, target, null);
}
/// <summary>
/// CopyProperty 将source中的属性的值赋给target上想匹配的属性匹配关系通过propertyMapItemList确定
/// </summary>
public static void CopyProperty(object source, object target, IList<MapItem> propertyMapItemList)
{
Type sourceType = source.GetType();
Type targetType = target.GetType();
PropertyInfo[] sourcePros = sourceType.GetProperties();
if (propertyMapItemList != null)
{
foreach (MapItem item in propertyMapItemList)
{
object val = ReflectionHelper.GetProperty(source, item.Source);
ReflectionHelper.SetProperty(target, item.Target, val);
}
}
else
{
foreach (PropertyInfo sourceProperty in sourcePros)
{
if (sourceProperty.CanRead)
{
object val = ReflectionHelper.GetProperty(source, sourceProperty.Name);
ReflectionHelper.SetProperty(target, sourceProperty.Name, val);
}
}
}
}
#endregion
#region GetAllMethodsSearchMethod
/// <summary>
/// GetAllMethods 获取接口的所有方法信息,包括继承的
/// </summary>
public static IList<MethodInfo> GetAllMethods(params Type[] interfaceTypes)
{
foreach (Type interfaceType in interfaceTypes)
{
if (!interfaceType.IsInterface)
{
throw new Exception("Target Type must be interface!");
}
}
IList<MethodInfo> list = new List<MethodInfo>();
foreach (Type interfaceType in interfaceTypes)
{
ReflectionHelper.DistillMethods(interfaceType, ref list);
}
return list;
}
private static void DistillMethods(Type interfaceType, ref IList<MethodInfo> methodList)
{
foreach (MethodInfo meth in interfaceType.GetMethods())
{
bool isExist = false;
foreach (MethodInfo temp in methodList)
{
if ((temp.Name == meth.Name) && (temp.ReturnType == meth.ReturnType))
{
ParameterInfo[] para1 = temp.GetParameters();
ParameterInfo[] para2 = meth.GetParameters();
if (para1.Length == para2.Length)
{
bool same = true;
for (int i = 0; i < para1.Length; i++)
{
if (para1[i].ParameterType != para2[i].ParameterType)
{
same = false;
}
}
if (same)
{
isExist = true;
break;
}
}
}
}
if (!isExist)
{
methodList.Add(meth);
}
}
foreach (Type superInterfaceType in interfaceType.GetInterfaces())
{
ReflectionHelper.DistillMethods(superInterfaceType, ref methodList);
}
}
/// <summary>
/// SearchGenericMethodInType 搜索指定类型定义的泛型方法,不包括继承的。
/// </summary>
public static MethodInfo SearchGenericMethodInType(Type originType, string methodName, Type[] argTypes)
{
foreach (MethodInfo method in originType.GetMethods())
{
if (method.ContainsGenericParameters && method.Name == methodName)
{
bool succeed = true;
ParameterInfo[] paras = method.GetParameters();
if (paras.Length == argTypes.Length)
{
for (int i = 0; i < paras.Length; i++)
{
if (!paras[i].ParameterType.IsGenericParameter) //跳过泛型参数
{
if (paras[i].ParameterType.IsGenericType) //如果参数本身就是泛型类型如IList<T>
{
if (paras[i].ParameterType.GetGenericTypeDefinition() != argTypes[i].GetGenericTypeDefinition())
{
succeed = false;
break;
}
}
else //普通类型的参数
{
if (paras[i].ParameterType != argTypes[i])
{
succeed = false;
break;
}
}
}
}
if (succeed)
{
return method;
}
}
}
}
return null;
}
/// <summary>
/// SearchMethod 包括被继承的所有方法,也包括泛型方法。
/// </summary>
public static MethodInfo SearchMethod(Type originType, string methodName, Type[] argTypes)
{
MethodInfo meth = originType.GetMethod(methodName, argTypes);
if (meth != null)
{
return meth;
}
meth = ReflectionHelper.SearchGenericMethodInType(originType, methodName, argTypes);
if (meth != null)
{
return meth;
}
//搜索基类
Type baseType = originType.BaseType;
if (baseType != null)
{
while (baseType != typeof(object))
{
MethodInfo target = baseType.GetMethod(methodName, argTypes);
if (target != null)
{
return target;
}
target = ReflectionHelper.SearchGenericMethodInType(baseType, methodName, argTypes);
if (target != null)
{
return target;
}
baseType = baseType.BaseType;
}
}
//搜索基接口
if (originType.GetInterfaces() != null)
{
IList<MethodInfo> list = ReflectionHelper.GetAllMethods(originType.GetInterfaces());
foreach (MethodInfo theMethod in list)
{
if (theMethod.Name != methodName)
{
continue;
}
ParameterInfo[] args = theMethod.GetParameters();
if (args.Length != argTypes.Length)
{
continue;
}
bool correctArgType = true;
for (int i = 0; i < args.Length; i++)
{
if (args[i].ParameterType != argTypes[i])
{
correctArgType = false;
break;
}
}
if (correctArgType)
{
return theMethod;
}
}
}
return null;
}
#endregion
#region GetFullMethodName
public static string GetMethodFullName(MethodInfo method)
{
return string.Format("{0}.{1}()", method.DeclaringType, method.Name);
}
#endregion
}
}

View File

@@ -0,0 +1,65 @@
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace NetWorkHelper
{
/// <summary>
/// 负责将对象序列化成byte[]数组
/// </summary>
public class SerHelper
{
/// <summary>
/// 将实体序列化成byte[]数组
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static byte[] Serialize(object obj)
{
// 1.0 实例化流的序列化帮助类
BinaryFormatter bf = new BinaryFormatter();
//2.0 定义内存流用来接收通过bf的Serialize方法将obj对象序列化成byte[]字节数组
byte[] res;
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, obj);
res = ms.ToArray();
}
return res;
}
/// <summary>
/// 根据byte[]字节数组反序列化成 对象实体
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static T Deserialize<T>(byte[] buffer)
{
// 1.0 实例化流的序列化帮助类
BinaryFormatter bf = new BinaryFormatter();
T obj;
using (MemoryStream ms = new MemoryStream(buffer))
{
obj = (T)bf.Deserialize(ms);
}
//bf.Deserialize(
return obj;
}
/// <summary>
/// 根据byte[]字节数组反序列化成 对象实体
/// </summary>
/// <param name="datas"></param>
/// <param name="index"></param>
/// <returns></returns>
public static object Deserialize(byte[] datas, int index)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream stream = new MemoryStream(datas, index, datas.Length - index);
object obj = bf.Deserialize(stream);
stream.Dispose();
return obj;
}
}
}

View File

@@ -0,0 +1,293 @@
using System;
namespace NetWorkHelper.Helper
{
public static class TypeHelper
{
#region IsSimpleType
/// <summary>
/// IsSimpleType 是否为简单类型数值、字符、字符串、日期、布尔、枚举、Type
/// </summary>
public static bool IsSimpleType(Type t)
{
if (TypeHelper.IsNumbericType(t))
{
return true;
}
if (t == typeof(char))
{
return true;
}
if (t == typeof(string))
{
return true;
}
if (t == typeof(bool))
{
return true;
}
if (t == typeof(DateTime))
{
return true;
}
if (t == typeof(Type))
{
return true;
}
if (t.IsEnum)
{
return true;
}
return false;
}
#endregion
#region IsNumbericType
public static bool IsNumbericType(Type destDataType)
{
if ((destDataType == typeof(int)) || (destDataType == typeof(uint)) || (destDataType == typeof(double))
|| (destDataType == typeof(short)) || (destDataType == typeof(ushort)) || (destDataType == typeof(decimal))
|| (destDataType == typeof(long)) || (destDataType == typeof(ulong)) || (destDataType == typeof(float))
|| (destDataType == typeof(byte)) || (destDataType == typeof(sbyte)))
{
return true;
}
return false;
}
#endregion
#region IsIntegerCompatibleType
public static bool IsIntegerCompatibleType(Type destDataType)
{
if ((destDataType == typeof(int)) || (destDataType == typeof(uint)) || (destDataType == typeof(short)) || (destDataType == typeof(ushort))
|| (destDataType == typeof(long)) || (destDataType == typeof(ulong)) || (destDataType == typeof(byte)) || (destDataType == typeof(sbyte)))
{
return true;
}
return false;
}
#endregion
#region GetClassSimpleName
/// <summary>
/// GetClassSimpleName 获取class的声明名称如 Person
/// </summary>
public static string GetClassSimpleName(Type t)
{
string[] parts = t.ToString().Split('.');
return parts[parts.Length - 1].ToString();
}
#endregion
#region IsFixLength
public static bool IsFixLength(Type destDataType)
{
if (TypeHelper.IsNumbericType(destDataType))
{
return true;
}
if (destDataType == typeof(byte[]))
{
return true;
}
if ((destDataType == typeof(DateTime)) || (destDataType == typeof(bool)))
{
return true;
}
return false;
}
#endregion
#region ChangeType
/// <summary>
/// ChangeType 对System.Convert.ChangeType进行了增强支持(0,1)到bool的转换字符串->枚举、int->枚举、字符串->Type
/// </summary>
public static object ChangeType(Type targetType, object val)
{
#region null
if (val == null)
{
return null;
}
#endregion
if (targetType.IsAssignableFrom(val.GetType()))
{
return val;
}
#region Same Type
if (targetType == val.GetType())
{
return val;
}
#endregion
#region bool 1,0
if (targetType == typeof(bool))
{
if (val.ToString() == "0")
{
return false;
}
if (val.ToString() == "1")
{
return true;
}
}
#endregion
#region Enum
if (targetType.IsEnum)
{
int intVal = 0;
bool suc = int.TryParse(val.ToString(), out intVal);
if (!suc)
{
return Enum.Parse(targetType, val.ToString());
}
else
{
return val;
}
}
#endregion
#region Type
if (targetType == typeof(Type))
{
return ReflectionHelper.GetType(val.ToString());
}
#endregion
if (targetType == typeof(IComparable))
{
return val;
}
//将double赋值给数值型的DataRow的字段是可以的但是通过反射赋值给object的非double的其它数值类型的属性却不行
return System.Convert.ChangeType(val, targetType);
}
#endregion
#region GetDefaultValue
public static object GetDefaultValue(Type destType)
{
if (TypeHelper.IsNumbericType(destType))
{
return 0;
}
if (destType == typeof(string))
{
return "";
}
if (destType == typeof(bool))
{
return false;
}
if (destType == typeof(DateTime))
{
return DateTime.Now;
}
if (destType == typeof(Guid))
{
return System.Guid.NewGuid();
}
if (destType == typeof(TimeSpan))
{
return System.TimeSpan.Zero;
}
return null;
}
#endregion
#region GetDefaultValueString
public static string GetDefaultValueString(Type destType)
{
if (TypeHelper.IsNumbericType(destType))
{
return "0";
}
if (destType == typeof(string))
{
return "\"\"";
}
if (destType == typeof(bool))
{
return "false";
}
if (destType == typeof(DateTime))
{
return "DateTime.Now";
}
if (destType == typeof(Guid))
{
return "System.Guid.NewGuid()";
}
if (destType == typeof(TimeSpan))
{
return "System.TimeSpan.Zero";
}
return "null";
}
#endregion
#region GetTypeRegularName
/// <summary>
/// GetTypeRegularName 获取类型的完全名称,如"ESBasic.Filters.SourceFilter,ESBasic"
/// </summary>
public static string GetTypeRegularName(Type destType)
{
string assName = destType.Assembly.FullName.Split(',')[0];
return string.Format("{0},{1}", destType.ToString(), assName);
}
public static string GetTypeRegularNameOf(object obj)
{
Type destType = obj.GetType();
return TypeHelper.GetTypeRegularName(destType);
}
#endregion
#region GetTypeByRegularName
/// <summary>
/// GetTypeByFullString 通过类型的完全名称获取类型regularName如"ESBasic.Filters.SourceFilter,ESBasic"
/// </summary>
public static Type GetTypeByRegularName(string regularName)
{
return ReflectionHelper.GetType(regularName);
}
#endregion
}
}

View File

@@ -0,0 +1,269 @@
/********************************************************************
* *
* * Copyright (C) 2013-2018 uiskin.cn
* * 作者: BinGoo QQ315567586
* * 请尊重作者劳动成果,请保留以上作者信息,禁止用于商业活动。
* *
* * 创建时间2014-08-05
* * 说明Windows帮助类
* *
********************************************************************/
using Microsoft.Win32;
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace NetWorkHelper.Helper
{
public class WindowsHelper
{
#region
/// <summary>
/// 开机自动启动,使用注册表
/// </summary>
/// <param name="started">是否开机自动启动</param>
/// <param name="name">取一个唯一的注册表Key名称</param>
/// <param name="path">启动程序的完整路径</param>
public static void RunWhenStart_usingReg(bool started, string name, string path)
{
RegistryKey HKLM = Registry.LocalMachine;
try
{
RegistryKey run = HKLM.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\");
if (run == null)
{
return;
}
if (started)
{
run.SetValue(name, path);
}
else
{
object val = run.GetValue(name);
if (val != null)
{
run.DeleteValue(name);
}
}
}
finally
{
HKLM.Close();
}
}
#endregion
#region MouseEvent /
/// <summary>
/// MouseEvent 模拟鼠标点击
/// </summary>
[DllImport("user32.dll", EntryPoint = "mouse_event")]
public static extern void MouseEvent(MouseEventFlag flags, int dx, int dy, uint data, UIntPtr extraInfo);
//在(34, 258)处点击鼠标
//SetCursorPos(34, 258);
//MouseEvent(MouseEventFlag.LeftDown, 0, 0, 0, UIntPtr.Zero);
//MouseEvent(MouseEventFlag.LeftUp, 0, 0, 0, UIntPtr.Zero);
/// <summary>
/// SetCursorPos 设置光标的绝对位置
/// </summary>
[DllImport("user32.dll")]
public static extern bool SetCursorPos(int x, int y);
/// <summary>
/// KeybdEvent 模拟键盘。已经过期。
/// </summary>
[DllImport("user32.dll", EntryPoint = "keybd_event")]
public static extern void KeybdEvent2(byte key, byte bScan, KeybdEventFlag flags, uint dwExtraInfo);
public static void KeybdEvent(byte key, byte bScan, KeybdEventFlag flags, uint dwExtraInfo)
{
INPUT input = new INPUT();
input.type = 1; //keyboard
input.ki.wVk = key;
input.ki.wScan = MapVirtualKey(key, 0);
input.ki.dwFlags = (int)flags;
SendInput(1, ref input, Marshal.SizeOf(input));
}
[DllImport("user32.dll")]
private static extern UInt32 SendInput(UInt32 nInputs, ref INPUT pInputs, int cbSize);
[DllImport("user32.dll")]
private static extern byte MapVirtualKey(byte wCode, int wMap);
#endregion
#region
/// <summary>
/// 根据扩展名获取系统图标。
/// </summary>
/// <param name="fileType">文件类型,使用扩展名表示,如".txt"</param>
public static Icon GetSystemIconByFileType(string fileType, bool isLarge)
{
if (isLarge)
{
return GetIcon(fileType, FILE_ATTRIBUTE.NORMAL, SHGFI.USEFILEATTRIBUTES | SHGFI.ICON | SHGFI.LARGEICON);
}
return GetIcon(fileType, FILE_ATTRIBUTE.NORMAL, SHGFI.USEFILEATTRIBUTES | SHGFI.ICON | SHGFI.SMALLICON);
}
private static Icon GetIcon(string path, FILE_ATTRIBUTE dwAttr, SHGFI dwFlag)
{
SHFILEINFO fi = new SHFILEINFO();
Icon ic = null;
int iTotal = (int)SHGetFileInfo(path, dwAttr, ref fi, 0, dwFlag);
ic = Icon.FromHandle(fi.hIcon);
return ic;
}
#region shell32函数
[DllImport("shell32", EntryPoint = "SHGetFileInfo", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SHGetFileInfo(string pszPath, FILE_ATTRIBUTE dwFileAttributes, ref SHFILEINFO sfi, int cbFileInfo, SHGFI uFlags);
// Contains information about a file object
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct SHFILEINFO
{
public IntPtr hIcon; //文件的图标句柄
public IntPtr iIcon; //图标的系统索引号
public uint dwAttributes; //文件的属性值
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName; //文件的显示名
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName; //文件的类型名
};
// Flags that specify the file information to retrieve with SHGetFileInfo
[Flags]
public enum SHGFI : uint
{
ADDOVERLAYS = 0x20,
ATTR_SPECIFIED = 0x20000,
ATTRIBUTES = 0x800, //获得属性
DISPLAYNAME = 0x200, //获得显示名
EXETYPE = 0x2000,
ICON = 0x100, //获得图标
ICONLOCATION = 0x1000,
LARGEICON = 0, //获得大图标
LINKOVERLAY = 0x8000,
OPENICON = 2,
OVERLAYINDEX = 0x40,
PIDL = 8,
SELECTED = 0x10000,
SHELLICONSIZE = 4,
SMALLICON = 1, //获得小图标
SYSICONINDEX = 0x4000,
TYPENAME = 0x400, //获得类型名
USEFILEATTRIBUTES = 0x10
}
// Flags that specify the file information to retrieve with SHGetFileInfo
[Flags]
public enum FILE_ATTRIBUTE
{
READONLY = 0x00000001,
HIDDEN = 0x00000002,
SYSTEM = 0x00000004,
DIRECTORY = 0x00000010,
ARCHIVE = 0x00000020,
DEVICE = 0x00000040,
NORMAL = 0x00000080,
TEMPORARY = 0x00000100,
SPARSE_FILE = 0x00000200,
REPARSE_POINT = 0x00000400,
COMPRESSED = 0x00000800,
OFFLINE = 0x00001000,
NOT_CONTENT_INDEXED = 0x00002000,
ENCRYPTED = 0x00004000
}
#endregion
#endregion
#region TopLevel在最前
[DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
private static extern bool SetActiveWindow(IntPtr hWnd);
/// <summary>
/// 设置目标窗体为活动窗体将其TopLevel在最前。
/// </summary>
public static void SetForegroundWindow(Form window)
{
SetActiveWindow(window.Handle);
}
#endregion
}
#region MouseEventFlag ,KeybdEventFlag
/// <summary>
/// 模拟鼠标点击的相关标志 。
/// </summary>
[Flags]
public enum MouseEventFlag : uint
{
Move = 0x0001,
LeftDown = 0x0002,
LeftUp = 0x0004,
RightDown = 0x0008,
RightUp = 0x0010,
MiddleDown = 0x0020,
MiddleUp = 0x0040,
XDown = 0x0080,
XUp = 0x0100,
Wheel = 0x0800,
VirtualDesk = 0x4000,
Absolute = 0x8000 //绝对坐标
}
/// <summary>
/// 模拟键盘点击的相关标志 。
/// </summary>
[Flags]
public enum KeybdEventFlag : uint
{
Down = 0,
Up = 0x0002
}
#endregion
[StructLayout(LayoutKind.Explicit)]
public struct INPUT
{
[FieldOffset(0)]
public Int32 type;
[FieldOffset(4)]
public KEYBDINPUT ki;
[FieldOffset(4)]
public MOUSEINPUT mi;
[FieldOffset(4)]
public HARDWAREINPUT hi;
}
[StructLayout(LayoutKind.Sequential)]
public struct MOUSEINPUT
{
public Int32 dx;
public Int32 dy;
public Int32 mouseData;
public Int32 dwFlags;
public Int32 time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
public struct KEYBDINPUT
{
public Int16 wVk;
public Int16 wScan;
public Int32 dwFlags;
public Int32 time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
public struct HARDWAREINPUT
{
public Int32 uMsg;
public Int16 wParamL;
public Int16 wParamH;
}
}

View File

@@ -0,0 +1,166 @@
/********************************************************************
* *
* * Copyright (C) 2013-2018 uiskin.cn
* * 作者: BinGoo QQ315567586
* * 请尊重作者劳动成果,请保留以上作者信息,禁止用于商业活动。
* *
* * 创建时间2014-08-05
* * 说明实体类与XML互转帮助类
* *
********************************************************************/
using System;
using System.IO;
using System.Xml.Serialization;
namespace NetWorkHelper.Helper
{
/// <summary>
/// 实体类与XML互转多用于保存配置文件
/// </summary>
public class XmlHelper
{
#region
/// <summary>
/// 反序列化返回实体类
/// </summary>
/// <param name="type">类型</param>
/// <param name="xml">XML字符串</param>
/// <returns>返回实体类</returns>
public static object Deserialize(Type type, string xml)
{
try
{
using (StringReader sr = new StringReader(xml))
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(sr);
}
}
catch (Exception e)
{
return null;
}
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="type"></param>
/// <param name="xml"></param>
/// <returns></returns>
public static object Deserialize(Type type, Stream stream)
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(stream);
}
#endregion
#region
/// <summary>
/// 序列化返回XML字符串
/// </summary>
/// <param name="type">类型</param>
/// <param name="obj">对象</param>
/// <returns>返回XML字符串</returns>
public static string Serializer(Type type, object obj)
{
MemoryStream Stream = new MemoryStream();
XmlSerializer xml = new XmlSerializer(type);
try
{
//序列化对象
xml.Serialize(Stream, obj);
}
catch (InvalidOperationException)
{
throw;
}
Stream.Position = 0;
StreamReader sr = new StreamReader(Stream);
string str = sr.ReadToEnd();
sr.Dispose();
Stream.Dispose();
return str;
}
#endregion
#region XML字符串文件
/// <summary>
/// 写XML字符串文件
/// </summary>
/// <param name="datafilePath"></param>
/// <param name="dataFileName"></param>
/// <param name="message"></param>
public static void WriteXmlData(string datafilePath, string dataFileName, string message)
{
//DirectoryInfo path=new DirectoryInfo(DataFileName);
//如果数据文件目录不存在,则创建
if (!Directory.Exists(datafilePath))
{
Directory.CreateDirectory(datafilePath);
}
FileInfo finfo = new FileInfo(datafilePath + dataFileName);
try
{
using (FileStream fs = new FileStream(datafilePath + dataFileName, FileMode.Create))
{
using (StreamWriter strwriter = new StreamWriter(fs))
{
try
{
strwriter.WriteLine(message);
strwriter.Flush();
}
catch (Exception ex)
{
Console.WriteLine(string.Format("数据文件写入失败信息:{0},行号{1}", ex.Message, ex.StackTrace));
}
}
}
}
catch (Exception ee)
{
Console.WriteLine(string.Format("数据文件没有打开,详细信息如下:{0}", ee.Message));
}
}
#endregion
#region XML文件
/// <summary>
/// 读取XML文件
/// </summary>
/// <param name="fileName">文件名(包含路径)</param>
/// <returns>返回文件字符串</returns>
public static string ReadXmlFile(string fileName)
{
//异常检测开始
try
{
string fileContent = "";
using (var reader = new StreamReader(fileName))
{
fileContent = reader.ReadToEnd();
}
return fileContent;
}
catch
{
//抛出异常
return "";
}
//异常检测结束
}
#endregion
}
}

View File

@@ -0,0 +1,38 @@
namespace NetWorkHelper.IBase
{
/// <summary>
/// MapItem 映射项。
/// </summary>
public class MapItem
{
#region
public MapItem()
{
}
public MapItem(string theSource, string theTarget)
{
this.source = theSource;
this.target = theTarget;
}
#endregion
#region Source
private string source;
public string Source
{
get { return source; }
set { source = value; }
}
#endregion
#region Target
private string target;
public string Target
{
get { return target; }
set { target = value; }
}
#endregion
}
}

View File

@@ -0,0 +1,139 @@
using NetWorkHelper.Helper;
using NetWorkHelper.ICommond;
using System;
using System.Collections.Generic;
namespace NetWorkHelper.ICollections
{
/// <summary>
/// CollectionConverter 用于转换集合内的元素或集合类型。
/// </summary>
public static class CollectionConverter
{
#region ConvertAll
/// <summary>
/// ConvertAll 将source中的每个元素转换为TResult类型
/// </summary>
public static List<TResult> ConvertAll<TObject, TResult>(IEnumerable<TObject> source, CommonMethod.Func<TObject, TResult> converter)
{
return CollectionConverter.ConvertSpecification<TObject, TResult>(source, converter, null);
}
#endregion
#region ConvertSpecification
/// <summary>
/// ConvertSpecification 将source中的符合predicate条件元素转换为TResult类型
/// </summary>
public static List<TResult> ConvertSpecification<TObject, TResult>(IEnumerable<TObject> source, CommonMethod.Func<TObject, TResult> converter, Predicate<TObject> predicate)
{
List<TResult> list = new List<TResult>();
CollectionHelper.ActionOnSpecification<TObject>(source, delegate (TObject ele) { list.Add(converter(ele)); }, predicate);
return list;
}
#endregion
#region ConvertFirstSpecification
/// <summary>
/// ConvertSpecification 将source中的符合predicate条件的第一个元素转换为TResult类型
/// </summary>
public static TResult ConvertFirstSpecification<TObject, TResult>(IEnumerable<TObject> source, CommonMethod.Func<TObject, TResult> converter, Predicate<TObject> predicate)
{
TObject target = CollectionHelper.FindFirstSpecification<TObject>(source, predicate);
if (target == null)
{
return default(TResult);
}
return converter(target);
}
#endregion
#region CopyAllToList
public static List<TObject> CopyAllToList<TObject>(IEnumerable<TObject> source)
{
List<TObject> copy = new List<TObject>();
CollectionHelper.ActionOnEach<TObject>(source, delegate (TObject t) { copy.Add(t); });
return copy;
}
#endregion
#region CopySpecificationToList
public static List<TObject> CopySpecificationToList<TObject>(IEnumerable<TObject> source, Predicate<TObject> predicate)
{
List<TObject> copy = new List<TObject>();
CollectionHelper.ActionOnSpecification<TObject>(source, delegate (TObject t) { copy.Add(t); }, predicate);
return copy;
}
#endregion
#region ConvertListUpper
/// <summary>
/// ConvertListUpper 将子类对象集合转换为基类对象集合
/// </summary>
public static List<TBase> ConvertListUpper<TBase, T>(IList<T> list) where T : TBase
{
List<TBase> baseList = new List<TBase>(list.Count);
for (int i = 0; i < list.Count; i++)
{
baseList.Add(list[i]);
}
return baseList;
}
#endregion
#region ConvertListDown
/// <summary>
/// ConvertListDown 将基类对象集合强制转换为子类对象集合
/// </summary>
public static List<T> ConvertListDown<TBase, T>(IList<TBase> baseList) where T : TBase
{
List<T> list = new List<T>(baseList.Count);
for (int i = 0; i < baseList.Count; i++)
{
list.Add((T)baseList[i]);
}
return list;
}
#endregion
#region ConvertArrayToList
/// <summary>
/// ConverArrayToList 将数组转换为List
/// </summary>
public static List<TElement> ConvertArrayToList<TElement>(TElement[] ary)
{
if (ary == null)
{
return null;
}
return CollectionHelper.Find<TElement>(ary, null);
}
#endregion
#region ConvertListToArray
/// <summary>
/// ConverListToArray 将List转换为数组
/// </summary>
public static TElement[] ConvertListToArray<TElement>(IList<TElement> list)
{
if (list == null)
{
return null;
}
TElement[] ary = new TElement[list.Count];
for (int i = 0; i < ary.Length; i++)
{
ary[i] = list[i];
}
return ary;
}
#endregion
}
}

View File

@@ -0,0 +1,672 @@
using System;
using System.Collections.Generic;
using System.Threading;
namespace NetWorkHelper.ICollections
{
/// <summary>
/// 有序的数组SortedArray 中的元素是不允许重复的。如果添加数组中已经存在的元素,将会被忽略。
/// 该实现是线程安全的。
/// </summary>
[Serializable]
public class SortedArray<T> : SortedArray2<T>, IComparer<T> where T : IComparable
{
public SortedArray()
{
base.comparer4Key = this;
}
public SortedArray(ICollection<T> collection)
{
base.comparer4Key = this;
base.Rebuild(collection);
}
#region IComparer<TKey>
public int Compare(T x, T y)
{
return x.CompareTo(y);
}
#endregion
}
/// <summary>
/// 有序的数组SortedArray 中的元素是不允许重复的。如果添加数组中已经存在的元素,将会被忽略。
/// 该实现是线程安全的。
/// </summary>
[Serializable]
public class SortedArray2<T>
{
private List<T> lazyCopy = null;
private int minCapacityForShrink = 32;
private T[] array = new T[32];
private int validCount = 0;
protected IComparer<T> comparer4Key = null;
#region SmartRWLocker
[NonSerialized] private SmartRWLocker smartRWLocker = new SmartRWLocker();
private SmartRWLocker SmartRWLocker
{
get
{
if (smartRWLocker == null)
{
smartRWLocker = new SmartRWLocker();
}
return smartRWLocker;
}
}
#endregion
#region Ctor
protected SortedArray2()
{
}
public SortedArray2(IComparer<T> comparer)
{
this.comparer4Key = comparer;
}
public SortedArray2(IComparer<T> comparer, ICollection<T> collection)
{
this.comparer4Key = comparer;
Rebuild(collection);
}
protected void Rebuild(ICollection<T> collection)
{
if (collection == null || collection.Count == 0)
{
return;
}
this.array = new T[collection.Count];
collection.CopyTo(this.array, 0);
Array.Sort(this.array, this.comparer4Key);
this.validCount = collection.Count;
}
#endregion
#region Property
#region Count
public int Count
{
get { return this.validCount; }
}
#endregion
#region Capacity
private int Capacity
{
get { return this.array.Length; }
}
#endregion
#region LastReadTime
public DateTime LastReadTime
{
get { return this.SmartRWLocker.LastRequireReadTime; }
}
#endregion
#region LastWriteTime
public DateTime LastWriteTime
{
get { return this.SmartRWLocker.LastRequireWriteTime; }
}
#endregion
#endregion
#region Contains
public bool Contains(T t)
{
return this.IndexOf(t) >= 0;
}
#endregion
#region Index
public T this[int index]
{
get
{
using (this.SmartRWLocker.Lock(AccessMode.Read))
{
if (index < 0 || (index >= this.validCount))
{
throw new Exception("Index out of the range !");
}
return this.array[index];
}
}
}
#endregion
#region IndexOf
public int IndexOf(T t)
{
using (this.SmartRWLocker.Lock(AccessMode.Read))
{
if (this.validCount == 0)
{
return -1;
}
int index = Array.BinarySearch<T>(this.array, 0, this.validCount, t, this.comparer4Key);
return (index < 0) ? -1 : index;
}
}
#endregion
#region Add
public void Add(T t)
{
int posIndex = 0;
this.Add(t, out posIndex);
}
/// <summary>
/// Add 将一个元素添加到数组中。如果数组中已存在目标元素则忽略。无论哪种情况posIndex都会被赋予正确的值。
/// </summary>
public void Add(T t, out int posIndex)
{
if (t == null)
{
throw new Exception("Target can't be null !");
}
using (this.SmartRWLocker.Lock(AccessMode.Write))
{
int index = Array.BinarySearch<T>(this.array, 0, this.validCount, t, this.comparer4Key);
if (index >= 0)
{
posIndex = index;
return;
}
this.AdjustCapacity(1);
posIndex = ~index;
Array.Copy(this.array, posIndex, this.array, posIndex + 1, this.validCount - posIndex);
this.array[posIndex] = t;
++this.validCount;
}
this.lazyCopy = null;
}
public void Add(ICollection<T> collection)
{
this.Add(collection, true);
}
/// <summary>
/// Add 如果能保证collection中的元素不会与现有的元素重复则checkRepeat可以传入false。
/// </summary>
public void Add(ICollection<T> collection, bool checkRepeat)
{
if (collection == null || collection.Count == 0)
{
return;
}
using (this.SmartRWLocker.Lock(AccessMode.Write))
{
ICollection<T> resultCollection = collection;
#region checkRepeat
if (checkRepeat)
{
Dictionary<T, T> dic = new Dictionary<T, T>();
foreach (T t in collection)
{
if (dic.ContainsKey(t) || this.Contains(t))
{
continue;
}
dic.Add(t, t);
}
resultCollection = dic.Keys;
}
#endregion
if (resultCollection.Count == 0)
{
return;
}
this.AdjustCapacity(resultCollection.Count);
foreach (T t in resultCollection)
{
this.array[this.validCount] = t;
++this.validCount;
}
Array.Sort<T>(this.array, 0, this.validCount, this.comparer4Key);
}
this.lazyCopy = null;
}
#endregion
#region Remove
#region Remove
/// <summary>
/// Remove 删除数组中所有值为t的元素。
/// </summary>
public void Remove(T t)
{
if (t == null)
{
return;
}
int index = -1;
do
{
index = this.IndexOf(t);
if (index >= 0)
{
this.RemoveAt(index);
}
} while (index >= 0);
this.lazyCopy = null;
}
#endregion
#region RemoveAt
public void RemoveAt(int index)
{
using (this.SmartRWLocker.Lock(AccessMode.Write))
{
if (index < 0 || (index >= this.validCount))
{
return;
}
if (index == this.validCount - 1)
{
this.array[index] = default(T);
}
else
{
Array.Copy(this.array, index + 1, this.array, index, this.validCount - index - 1);
}
--this.validCount;
}
this.lazyCopy = null;
}
#endregion
#region RemoveBetween
public void RemoveBetween(int minIndex, int maxIndex)
{
using (this.SmartRWLocker.Lock(AccessMode.Write))
{
minIndex = minIndex < 0 ? 0 : minIndex;
maxIndex = maxIndex >= this.validCount ? this.validCount - 1 : maxIndex;
if (maxIndex < minIndex)
{
return;
}
Array.Copy(this.array, maxIndex + 1, this.array, minIndex, this.validCount - maxIndex - 1);
this.validCount -= (maxIndex - minIndex + 1);
}
this.lazyCopy = null;
}
#endregion
#endregion
#region GetBetween
public T[] GetBetween(int minIndex, int maxIndex)
{
using (this.SmartRWLocker.Lock(AccessMode.Read))
{
minIndex = minIndex < 0 ? 0 : minIndex;
maxIndex = maxIndex >= this.validCount ? this.validCount - 1 : maxIndex;
if (maxIndex < minIndex)
{
return new T[0];
}
int count = maxIndex - minIndex - 1;
T[] result = new T[count];
Array.Copy(this.array, minIndex, result, 0, count);
return result;
}
}
#endregion
#region Shrink
/// <summary>
/// Shrink 将内部数组收缩到最小,释放内存。
/// </summary>
public void Shrink()
{
using (this.SmartRWLocker.Lock(AccessMode.Write))
{
if (this.array.Length == this.validCount)
{
return;
}
int len = this.validCount >= this.minCapacityForShrink ? this.validCount : this.minCapacityForShrink;
T[] newAry = new T[len];
Array.Copy(this.array, 0, newAry, 0, this.validCount);
this.array = newAry;
}
}
#endregion
#region AdjustCapacity
private void AdjustCapacity(int newCount)
{
using (this.SmartRWLocker.Lock(AccessMode.Write))
{
int totalCount = this.validCount + newCount;
if (this.array.Length >= totalCount)
{
return;
}
int newCapacity = this.array.Length;
while (newCapacity < totalCount)
{
newCapacity *= 2;
}
T[] newAry = new T[newCapacity];
Array.Copy(this.array, 0, newAry, 0, this.validCount);
this.array = newAry;
}
}
#endregion
#region GetMax
public T GetMax()
{
using (this.SmartRWLocker.Lock(AccessMode.Read))
{
if (this.validCount == 0)
{
throw new Exception("SortedArray is Empty !");
}
return this.array[this.validCount - 1];
}
}
#endregion
#region GetMin
public T GetMin()
{
using (this.SmartRWLocker.Lock(AccessMode.Read))
{
if (this.validCount == 0)
{
throw new Exception("SortedArray is Empty !");
}
return this.array[0];
}
}
#endregion
#region GetAll
public List<T> GetAll()
{
List<T> list = new List<T>();
using (this.SmartRWLocker.Lock(AccessMode.Read))
{
for (int i = 0; i < this.validCount; i++)
{
list.Add(this.array[i]);
}
}
return list;
}
#endregion
#region GetAllReadonly
/// <summary>
/// 注意内部使用了Lazy缓存返回的集合不可被修改。
/// </summary>
public List<T> GetAllReadonly()
{
if (this.lazyCopy != null)
{
return this.lazyCopy;
}
using (this.SmartRWLocker.Lock(AccessMode.Read))
{
List<T> list = new List<T>();
for (int i = 0; i < this.validCount; i++)
{
list.Add(this.array[i]);
}
this.lazyCopy = list;
return this.lazyCopy;
}
}
#endregion
#region Clear
public void Clear()
{
using (this.SmartRWLocker.Lock(AccessMode.Write))
{
this.array = new T[this.minCapacityForShrink];
this.validCount = 0;
}
this.lazyCopy = null;
}
#endregion
#region ToString
public override string ToString()
{
return string.Format("Count:{0} ,Capacity:{1}", this.validCount, this.array.Length);
}
#endregion
}
/// <summary>
/// SmartRWLocker 简化了ReaderWriterLock的使用。通过using来使用Lock方法返回的对象using(this.smartLocker.Lock(AccessMode.Read)){...}
/// zhuweisky 2008.11.25
/// </summary>
public class SmartRWLocker
{
private ReaderWriterLock readerWriterLock = new ReaderWriterLock();
#region LastRequireReadTime
private DateTime lastRequireReadTime = DateTime.Now;
public DateTime LastRequireReadTime
{
get { return lastRequireReadTime; }
}
#endregion
#region LastRequireWriteTime
private DateTime lastRequireWriteTime = DateTime.Now;
public DateTime LastRequireWriteTime
{
get { return lastRequireWriteTime; }
}
#endregion
#region Lock
public LockingObject Lock(AccessMode accessMode, bool enableSynchronize)
{
if (!enableSynchronize)
{
return null;
}
return this.Lock(accessMode);
}
public LockingObject Lock(AccessMode accessMode)
{
if (accessMode == AccessMode.Read)
{
this.lastRequireReadTime = DateTime.Now;
}
else
{
this.lastRequireWriteTime = DateTime.Now;
}
return new LockingObject(this.readerWriterLock, accessMode);
}
#endregion
}
/// <summary>
/// LockingObject SmartRWLocker的Lock方法返回的锁对象。仅仅通过using来使用该对象using(this.smartLocker.Lock(AccessMode.Read)){...}
/// </summary>
public class LockingObject : IDisposable
{
private ReaderWriterLock readerWriterLock;
private AccessMode accessMode = AccessMode.Read;
private LockCookie lockCookie;
#region Ctor
public LockingObject(ReaderWriterLock _lock, AccessMode _lockMode)
{
this.readerWriterLock = _lock;
this.accessMode = _lockMode;
if (this.accessMode == AccessMode.Read)
{
this.readerWriterLock.AcquireReaderLock(-1);
}
else if (this.accessMode == AccessMode.Write)
{
this.readerWriterLock.AcquireWriterLock(-1);
}
else //UpAndDowngrade
{
this.lockCookie = this.readerWriterLock.UpgradeToWriterLock(-1);
}
}
#endregion
#region IDisposable
public void Dispose()
{
if (this.accessMode == AccessMode.Read)
{
this.readerWriterLock.ReleaseReaderLock();
}
else if (this.accessMode == AccessMode.Write)
{
this.readerWriterLock.ReleaseWriterLock();
}
else //UpAndDowngrade
{
this.readerWriterLock.DowngradeFromWriterLock(ref this.lockCookie);
}
}
#endregion
}
/// <summary>
/// AccessMode 访问锁定资源的方式。
/// </summary>
public enum AccessMode
{
Read = 0,
Write,
/// <summary>
/// 前提条件已经获取Read锁。
/// 再采用此模式可以先升级到Write访问资源再降级回Read。
/// </summary>
UpAndDowngrade4Write
}
}

View File

@@ -0,0 +1,85 @@

using System.Net;
using System.Windows.Forms;
namespace NetWorkHelper.ICommond
{
public class CommonMethod
{
/// <summary>
/// 域名转换为IP地址
/// </summary>
/// <param name="hostname">域名或IP地址</param>
/// <returns>IP地址</returns>
internal static string HostnameToIp(string hostname)
{
try
{
IPAddress ip;
if (IPAddress.TryParse(hostname, out ip))
return ip.ToString();
else
return Dns.GetHostEntry(hostname).AddressList[0].ToString();
}
catch
{
throw;
}
}
/// <summary>
/// 外部调用是否需要用Invoket
/// </summary>
/// <param name="func">事件参数</param>
internal static void EventInvoket(Action func)
{
Form form = null;
if (Application.OpenForms.Count > 0)
{
form = Application.OpenForms[0];
}
//Form form = Application.OpenForms.Cast<Form>().FirstOrDefault();
if (form != null && form.InvokeRequired)
{
form.Invoke(func);
}
else
{
func();
}
}
/// <summary>
/// 具有返回值的 非bool 外部调用是否需要用Invoket
/// </summary>
/// <param name="func">方法</param>
/// <returns>返回客户操作之后的数据</returns>
internal static object EventInvoket(Func<object> func)
{
object haveStr;
Form form = null;
if (Application.OpenForms.Count > 0)
{
form = Application.OpenForms[0];
}
//Form form = Application.OpenForms.Cast<Form>().FirstOrDefault();
if (form != null && form.InvokeRequired)
{
haveStr = form.Invoke(func);
}
else
{
haveStr = func();
}
return haveStr;
}
public delegate void Action();
public delegate TResult Func<TResult>();
public delegate TResult Func<T, TResult>(T a);
public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);
public delegate TResult Func<T1, T2, T3, TResult>(T1 arg1, T2 arg2, T3 arg3);
public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
}
}

View File

@@ -0,0 +1,273 @@
/********************************************************************
* *
* * Copyright (C) 2013-2018 uiskin.cn
* * 作者: BinGoo QQ315567586
* * 请尊重作者劳动成果,请保留以上作者信息,禁止用于商业活动。
* *
* * 创建时间2014-08-05
* * 说明:事件委托类,用于事件的申明
* *
********************************************************************/
using NetWorkHelper.IModels;
using System;
namespace NetWorkHelper.ICommond
{
public class TcpServerReceviceaEventArgs : EventArgs
{
public TcpServerReceviceaEventArgs(IClient iClient, byte[] data)
{
IClient = iClient;
Data = data;
}
/// <summary>
/// 客户端
/// </summary>
public IClient IClient { get; set; }
/// <summary>
/// 接收到的原始数据
/// </summary>
public byte[] Data { get; set; }
}
public class TcpServerClientEventArgs : EventArgs
{
public TcpServerClientEventArgs(IClient iClient)
{
IClient = iClient;
}
/// <summary>
/// 客户端
/// </summary>
public IClient IClient { get; set; }
}
public class TcpServerStateEventArgs : EventArgs
{
public TcpServerStateEventArgs(IClient iClient, string msg, SocketState state)
{
IClient = iClient;
Msg = msg;
State = state;
}
/// <summary>
/// 客户端
/// </summary>
public IClient IClient { get; set; }
/// <summary>
/// 状态消息
/// </summary>
public string Msg { get; set; }
/// <summary>
/// 状态类型
/// </summary>
public SocketState State { get; set; }
}
public class TcpServerLogEventArgs : EventArgs
{
public TcpServerLogEventArgs(IClient iClient, LogType logType, string logMsg)
{
IClient = iClient;
LogType = logType;
LogMsg = logMsg;
}
/// <summary>
/// 客户端
/// </summary>
public IClient IClient { get; set; }
/// <summary>
/// 日志类型
/// </summary>
public LogType LogType { get; set; }
/// <summary>
/// 日志信息
/// </summary>
public string LogMsg { get; set; }
}
public class TcpServerErrorEventArgs : EventArgs
{
public TcpServerErrorEventArgs(string errorMsg)
{
ErrorMsg = errorMsg;
}
/// <summary>
/// 错误信息
/// </summary>
public string ErrorMsg { get; set; }
}
public class TcpServerSendReturnEventArgs : EventArgs
{
public TcpServerSendReturnEventArgs(IClient iClient, int byteLen)
{
IClient = iClient;
ByteLen = byteLen;
}
/// <summary>
/// 客户端
/// </summary>
public IClient IClient { get; set; }
/// <summary>
/// 成功发送的数据长度
/// </summary>
public int ByteLen { get; set; }
}
public class TcpServerReturnClientCountEventArgs : EventArgs
{
public TcpServerReturnClientCountEventArgs(int clientCount)
{
ClientCount = clientCount;
}
/// <summary>
/// 客户端数量
/// </summary>
public int ClientCount { get; set; }
}
public class TcpClientReceviceEventArgs : EventArgs
{
public TcpClientReceviceEventArgs(byte[] data)
{
Data = data;
}
/// <summary>
/// 接收到的原始数据
/// </summary>
public byte[] Data { get; set; }
}
public class TcpClientErrorEventArgs : EventArgs
{
public TcpClientErrorEventArgs(string errorMsg)
{
ErrorMsg = errorMsg;
}
/// <summary>
/// 错误信息
/// </summary>
public string ErrorMsg { get; set; }
}
public class TcpClientStateEventArgs : EventArgs
{
public TcpClientStateEventArgs(string stateInfo, SocketState state)
{
StateInfo = stateInfo;
State = state;
}
/// <summary>
/// 状态爱信息
/// </summary>
public string StateInfo { get; set; }
/// <summary>
/// 状态
/// </summary>
public SocketState State { get; set; }
}
public class HttpDownLoadEventArgs : EventArgs
{
public HttpDownLoadEventArgs(long totalSize, long curSize, int progress)
{
TotalSize = totalSize;
CurSize = curSize;
Progress = progress;
}
public long TotalSize { get; set; }
public long CurSize { get; set; }
public int Progress { get; set; }
}
#region
#region ITcpServer服务端事件委托
//public delegate void TcpServerReceviceEventHandler(IClient iClient, byte[] data);
//public delegate void TcpServerClientEventHandler(IClient iClient);
//public delegate void TcpServerStateEventHandler(IClient iClient, string msg, SocketState state);
//public delegate void TcpServerLogEventHandler(IClient iClient, LogType logType, string logMsg);
//public delegate void TcpServerErrorEventHandler(string errorMsg);
//public delegate void TcpServerSendReturnEventHandler(IClient iClient, int byteLen);
//public delegate void TcpServerReturnClientCountEventHandler(int clientCount);
#endregion
#region ITcpClient客户端事件委托
//public delegate void TcpClientReceviceEventHandler(byte[] data);
//public delegate void TcpClientErrorEventHandler(string errorMsg);
//public delegate void TcpClientStateEventHandler(string msg, SocketState state);
#endregion
#region 使
/// <summary>
/// 不带参数的委托
/// </summary>
public delegate void NetWorkEventHandler();
/// <summary>
/// 带一个参数的委托
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <param name="object1"></param>
public delegate void NetWorkEventHandler<T1>(T1 object1);
/// <summary>
/// 带两个参数的委托
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <param name="object1"></param>
/// <param name="object2"></param>
public delegate void NetWorkEventHandler<T1, T2>(T1 object1, T2 object2);
/// <summary>
/// 带三个参数的委托
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <typeparam name="T3"></typeparam>
/// <param name="object1"></param>
/// <param name="object2"></param>
/// <param name="object3"></param>
public delegate void NetWorkEventHandler<T1, T2, T3>(T1 object1, T2 object2, T3 object3);
/// <summary>
/// 带四个参数的委托
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <typeparam name="T3"></typeparam>
/// <typeparam name="T4"></typeparam>
/// <param name="object1"></param>
/// <param name="object2"></param>
/// <param name="object3"></param>
/// <param name="object4"></param>
public delegate void NetWorkEventHandler<T1, T2, T3, T4>(T1 object1, T2 object2, T3 object3, T4 object4);
/// <summary>
/// 带五个参数的委托
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <typeparam name="T3"></typeparam>
/// <typeparam name="T4"></typeparam>
/// <typeparam name="T5"></typeparam>
/// <param name="object1"></param>
/// <param name="object2"></param>
/// <param name="object3"></param>
/// <param name="object4"></param>
/// <param name="object5"></param>
public delegate void NetWorkEventHandler<T1, T2, T3, T4, T5>(T1 object1, T2 object2, T3 object3, T4 object4, T5 object5);
public delegate void NetWorkEventHandler<T1, T2, T3, T4, T5, T6>(T1 object1, T2 object2, T3 object3, T4 object4, T5 object5, T6 object6);
public delegate void NetWorkEventHandler<T1, T2, T3, T4, T5, T6, T7>(T1 object1, T2 object2, T3 object3, T4 object4, T5 object5, T6 object6, T7 object7);
public delegate void NetWorkEventHandler<T1, T2, T3, T4, T5, T6, T7, T8>(T1 object1, T2 object2, T3 object3, T4 object4, T5 object5, T6 object6, T7 object7, T8 object8);
public delegate void NetWorkEventHandler<T1, T2, T3, T4, T5, T6, T7, T8, T9>(T1 object1, T2 object2, T3 object3, T4 object4, T5 object5, T6 object6, T7 object7, T8 object8, T9 object9);
#endregion
#endregion
}

View File

@@ -0,0 +1,126 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Sockets;
using System.Text;
using SocketHelper.TClass;
namespace SocketHelper.IModels
{
/// <summary>
/// 此类在旧版本AxTcpServer组件中中使用
/// 客户端类
/// </summary>
public class ClientModel
{
private byte[] _bufferBackup = null;//备份缓冲区;主要是缓冲区有时候需要增大或缩小的时候用到;
/// <summary>
/// 备份缓冲区;主要是缓冲区有时候需要增大或缩小的时候用到;
/// </summary>
internal byte[] BufferBackup
{
get { return _bufferBackup; }
set { _bufferBackup = value; }
}
/// <summary>
/// 接受的数据缓存
/// </summary>
public string RecevidMsg = "";
/// <summary>
/// 缓存数据
/// </summary>
public List<byte> RecevidBuffer = new List<byte>();
/// <summary>
/// PC嵌套字
/// </summary>
public Socket ClientSocket;
/// <summary>
/// 客户端类型1
/// </summary>
public ClientType Clienttype = ClientType.None;
/// <summary>
/// Socket类型网页版或者PC版
/// </summary>
public ClientStyle ClientStyle = ClientStyle.PcSocket;
/// <summary>
/// 客户端编号
/// </summary>
public int Id = -1;
/// <summary>
/// 若是小车类型,则该标示表示车辆编号,若是信号机类型,则该标示表示信号机编号,其他则不使用该类型
/// </summary>
public string ClientNo = "";
/// <summary>
/// 如果是小车类型,则该项用于存储车辆运动状态,默认:运动
/// </summary>
public VehicleMotionState VehicleMotionState = VehicleMotionState.Running;
/// <summary>
/// 判断在停车位上的状态
/// </summary>
public SitState SitState = SitState.None;
public LedState[] SingleState = new LedState[0];
public LedState[] SidewalkState = new LedState[0];
/// <summary>
/// 若是小车类型则该标示表示小车单前的RFID卡号
/// </summary>
public string ClientRfidNo = "";
/// <summary>
/// 若是小车类型,则该标示表示小车单前的车道号
/// </summary>
public string ClientLaneNo = "";
/// <summary>
/// 若是PC客户端类型则下面两个表示表示用户登陆账号和密码
/// </summary>
public string Username = "";
public string Password = "";
//存储PC客户端当前需要订阅的车辆
public List<string> CarNo { get; set; }
/// <summary>
/// 如果是闸机,升降杆客户端,(用于存储各个控制端的状态)
/// </summary>
public byte[] MotorClientState = new byte[32];
/// <summary>
/// 是否登陆
/// </summary>
public bool IsLogin { get; set; }
/// <summary>
/// 是否授权
/// </summary>
public bool IsAuthorization { get; set; }
/// <summary>
/// 是否在线
/// </summary>
public bool IsOnline = true;
/// <summary>
/// 心跳包字符串【如果为空则不发送心跳包】
/// </summary>
public string Heartbeat = "";
public string OrderType = "";
/// <summary>
/// 承载客户端Socket的网络流
/// </summary>
public NetworkStream NetworkStream { get; set; }
/// <summary>
/// 发生异常时不为null.
/// </summary>
public Exception Exception { get; set; }
/// <summary>
/// 接收缓冲区
/// </summary>
public byte[] RecBuffer =new byte[1024];
/// <summary>
/// 发送缓冲区
/// </summary>
public byte[] SendBuffer { get; set; }
/// <summary>
/// 异步接收后包的大小
/// </summary>
public int Offset { get; set; }
}
}

View File

@@ -0,0 +1,198 @@
/********************************************************************
* *
* * 创建时间2014-08-05
* * 说明:客户端信息类,存储客户端的一些基本信息,可定义修改
* *
********************************************************************/
using NetWorkHelper.IUser;
using NetWorkHelper.TClass;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
namespace NetWorkHelper.IModels
{
public class IClient
{
public IClient()
{
ClientStyle = ClientStyle.PcSocket;
Username = "";
Password = "";
BufferInfo = new BufferInfo();
ClientInfo = new ClientInfo();
}
public IClient(Socket socket)
{
WorkSocket = socket;
if (socket != null)
{
Ip = ((IPEndPoint)WorkSocket.RemoteEndPoint).Address.ToString();
Port = ((IPEndPoint)WorkSocket.RemoteEndPoint).Port;
}
ClientStyle = ClientStyle.PcSocket;
Username = "";
Password = "";
BufferInfo = new BufferInfo();
ClientInfo = new ClientInfo();
}
/// <summary>
/// Socket
/// </summary>
public Socket WorkSocket { get; set; }
/// <summary>
/// 客户端端口IP
/// </summary>
public string Ip { get; set; }
/// <summary>
/// 客户端端口
/// </summary>
public int Port { get; set; }
/// <summary>
/// Socket类型网页版或者PC版
/// </summary>
public ClientStyle ClientStyle { get; set; }
/// <summary>
/// 客户端登录账号
/// </summary>
public string Username { get; set; }
/// <summary>
/// 客户端登录密码
/// </summary>
public string Password { get; set; }
/// <summary>
/// 客户端信息类
/// </summary>
public ClientInfo ClientInfo { get; set; }
/// <summary>
/// 数据缓存区信息
/// </summary>
public BufferInfo BufferInfo { get; set; }
/// <summary>
/// 自定义数据
/// </summary>
public object CustomData { get; set; }
/// <summary>
/// 是否已登录
/// </summary>
public bool IsLogin { get; set; }
}
public class ClientInfo
{
/// <summary>
/// 心跳检测模式
/// </summary>
public HeartCheckType HeartCheckType = HeartCheckType.EncodingString;
/// <summary>
/// 心跳包数组数据【如果长度为0为空则不发送心跳包】
/// </summary>
public byte[] HeartbeatByte = new byte[0];
/// <summary>
/// 心跳包字符串【如果为空则不发送心跳包】
/// </summary>
public string Heartbeat = "";
/// <summary>
/// 客户端ID
/// </summary>
public int ClientId { get; set; }
/// <summary>
/// 客户端编号
/// </summary>
public string ClientNo { get; set; }
/// <summary>
/// 客户端类型
/// </summary>
public ClientType Clienttype = ClientType.None;
/// <summary>
/// 若是小车类型则该标示表示小车单前的RFID卡号
/// </summary>
public string ClientRfidNo = "";
/// <summary>
/// 若是小车类型,则该标示表示小车单前的车道号
/// </summary>
public string ClientLaneNo = "";
/// <summary>
/// 如果是小车类型,则该项用于存储车辆运动状态,默认:运动
/// </summary>
public VehicleMotionState VehicleMotionState = VehicleMotionState.Running;
/// <summary>
/// 判断在停车位上的状态
/// </summary>
public SitState SitState = SitState.None;
/// <summary>
/// 如果是信号机类型,用来存储信号灯路口状态
/// </summary>
public LedState[] SingleState = new LedState[0];
/// <summary>
/// 如果是信号机类型,用来存储信号灯人行道状态
/// </summary>
public LedState[] SidewalkState = new LedState[0];
/// <summary>
/// 如果是闸机,升降杆客户端,(用于存储各个控制端的状态)
/// </summary>
public byte[] MotorClientState = new byte[32];
/// <summary>
/// 是否授权
/// </summary>
public bool IsAuthorization { get; set; }
/// <summary>
/// 指令操作类型
/// </summary>
public string OrderType = "";
/// <summary>
/// 如果是调度系统客户端则用来存储PC客户端当前需要订阅的车辆列表
/// </summary>
public List<string> CarNo { get; set; }
}
public class BufferInfo
{
//备份缓冲区
private byte[] _bufferBackup = null;
/// <summary>
/// 备份缓冲区;动态增大或缩小缓冲区的时候用到;
/// </summary>
internal byte[] BufferBackup
{
get { return _bufferBackup; }
set { _bufferBackup = value; }
}
/// <summary>
/// 接收缓冲区
/// </summary>
public byte[] ReceivedBuffer = new byte[2048];
/// <summary>
/// 发送缓冲区
/// </summary>
public byte[] SendBuffer = new byte[1024];
/// <summary>
/// 接收的字符串信息
/// </summary>
public string RecevidMsg = "";
}
/// <summary>
/// 心跳检测模式
/// </summary>
public enum HeartCheckType
{
/// <summary>
/// 字符串模式
/// </summary>
EncodingString,
/// <summary>
/// 十六进制字符串
/// </summary>
HexString,
/// <summary>
/// byte数组模式
/// </summary>
Byte
}
}

View File

@@ -0,0 +1,548 @@
/********************************************************************
* *
* * Copyright (C) 2013-2018 uiskin.cn
* * 作者: BinGoo QQ315567586
* * 请尊重作者劳动成果,请保留以上作者信息,禁止用于商业活动。
* *
* * 创建时间2017-09-18
* * 说明:字符串,数字转换管理类
* *
********************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace NetWorkHelper.ITool
{
public class ConvertStringManager
{
#region
/// <summary>
/// 十六进制字符串转为字节数组
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static byte[] StringToHexByteArray(string s)
{
try
{
s = s.Replace(" ", "");
if ((s.Length % 2) != 0)
s += " ";
byte[] returnBytes = new byte[s.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(s.Substring(i * 2, 2), 16);
return returnBytes;
}
catch
{
return new byte[0];
}
}
/// <summary>
/// 字节数组转为十六进制字符串
/// </summary>
/// <param name="data"></param>
/// <param name="intervalChar"></param>
/// <returns></returns>
public static string HexByteArrayToString(byte[] data, char intervalChar = ' ')
{
try
{
StringBuilder sb = new StringBuilder(data.Length * 3);
foreach (byte b in data)
{
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, intervalChar));
}
return sb.ToString().ToUpper();//将得到的字符全部以字母大写形式输出
}
catch
{
return "";
}
}
#endregion
#region
/// <summary>
/// 实现各进制数间的转换。ConvertBase("15",10,16)表示将十进制数15转换为16进制的数。
/// </summary>
/// <param name="value">要转换的值,即原值</param>
/// <param name="from">原值的进制,只能是2,8,10,16四个值。</param>
/// <param name="to">要转换到的目标进制只能是2,8,10,16四个值。</param>
public static string ConvertBase(string value, int from, int to)
{
try
{
int intValue = Convert.ToInt32(value, from); //先转成10进制
string result = Convert.ToString(intValue, to); //再转成目标进制
if (to == 2)
{
int resultLength = result.Length; //获取二进制的长度
switch (resultLength)
{
case 7:
result = "0" + result;
break;
case 6:
result = "00" + result;
break;
case 5:
result = "000" + result;
break;
case 4:
result = "0000" + result;
break;
case 3:
result = "00000" + result;
break;
}
}
return result;
}
catch
{
//LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
return "0";
}
}
#endregion
#region 使string转换成byte[]
/// <summary>
/// 使用指定字符集将string转换成byte[]
/// </summary>
/// <param name="text">要转换的字符串</param>
/// <param name="encoding">字符编码</param>
public static byte[] StringToBytes(string text, Encoding encoding)
{
return encoding.GetBytes(text);
}
#endregion
#region 使byte[]string
/// <summary>
/// 使用指定字符集将byte[]转换成string
/// </summary>
/// <param name="bytes">要转换的字节数组</param>
/// <param name="encoding">字符编码</param>
public static string BytesToString(byte[] bytes, Encoding encoding)
{
return encoding.GetString(bytes);
}
#endregion
#region byte[]int
/// <summary>
/// 将byte[]转换成int
/// </summary>
/// <param name="data">需要转换成整数的byte数组</param>
public static int BytesToInt32(byte[] data)
{
//如果传入的字节数组长度小于4,则返回0
if (data.Length < 4)
{
return 0;
}
//定义要返回的整数
int num = 0;
//如果传入的字节数组长度大于4,需要进行处理
if (data.Length >= 4)
{
//创建一个临时缓冲区
byte[] tempBuffer = new byte[4];
//将传入的字节数组的前4个字节复制到临时缓冲区
Buffer.BlockCopy(data, 0, tempBuffer, 0, 4);
//将临时缓冲区的值转换成整数并赋给num
num = BitConverter.ToInt32(tempBuffer, 0);
}
//返回整数
return num;
}
#endregion
#region
/// <summary>
/// 把字符串按照分隔符转换成 List
/// </summary>
/// <param name="str">源字符串</param>
/// <param name="speater">分隔符</param>
/// <returns></returns>
public static List<string> GetStrList(string str, char speater)
{
List<string> list = new List<string>();
string[] ss = str.Split(speater);
foreach (string s in ss)
{
if (!string.IsNullOrEmpty(s) && s != speater.ToString())
{
string strVal = s;
list.Add(strVal);
}
}
return list;
}
/// <summary>
/// 把字符串按照分隔符转换成数组
/// </summary>
/// <param name="str"></param>
/// <param name="speater">分隔符</param>
/// <returns></returns>
public static string[] GetStrArray(string str, char speater)
{
return str.Split(speater);
}
/// <summary>
/// 把 字符串列表 按照分隔符组装成 新字符串
/// </summary>
/// <param name="list"></param>
/// <param name="speater"></param>
/// <returns></returns>
public static string GetListToString(List<string> list, string speater)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.Count; i++)
{
if (i == list.Count - 1)
{
sb.Append(list[i]);
}
else
{
sb.Append(list[i]);
sb.Append(speater);
}
}
return sb.ToString();
}
#endregion
#region
/// <summary>
/// 删除最后结尾的一个逗号
/// </summary>
public static string DelLastComma(string str)
{
return str.Substring(0, str.LastIndexOf(","));
}
/// <summary>
/// 删除最后结尾的指定字符后的字符
/// </summary>
public static string DelLastChar(string str, string strchar)
{
return str.Substring(0, str.LastIndexOf(strchar));
}
#endregion
#region
/// <summary>
/// 转全角的函数(SBC case)
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string ToSbc(string input)
{
//半角转全角:
char[] c = input.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
if (c[i] == 32)
{
c[i] = (char)12288;
continue;
}
if (c[i] < 127)
c[i] = (char)(c[i] + 65248);
}
return new string(c);
}
/// <summary>
/// 转半角的函数(DBC case)
/// </summary>
/// <param name="input">输入</param>
/// <returns></returns>
public static string ToDbc(string input)
{
char[] c = input.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
if (c[i] == 12288)
{
c[i] = (char)32;
continue;
}
if (c[i] > 65280 && c[i] < 65375)
c[i] = (char)(c[i] - 65248);
}
return new string(c);
}
#endregion
#region
/// <summary>
/// 快速验证一个字符串是否符合指定的正则表达式。
/// </summary>
/// <param name="_express">正则表达式的内容。</param>
/// <param name="_value">需验证的字符串。</param>
/// <returns>是否合法的bool值。</returns>
public static bool QuickValidate(string _express, string _value)
{
if (_value == null) return false;
Regex myRegex = new Regex(_express);
if (_value.Length == 0)
{
return false;
}
return myRegex.IsMatch(_value);
}
#endregion
#region
/// <summary>
/// 指定字符串的固定长度,如果字符串小于固定长度,
/// 则在字符串的前面补足零可设置的固定长度最大为9位
/// </summary>
/// <param name="text">原始字符串</param>
/// <param name="limitedLength">字符串的固定长度</param>
/// <param name="repairStr">要填补的字符</param>
public static string RepairZero(string text, int limitedLength, string repairStr)
{
//补足完整的字符串
string temp = "";
//补足字符串
for (int i = 0; i < limitedLength - text.Length; i++)
{
temp += repairStr;
}
//连接text
temp += text;
//返回补足0的字符串
return temp;
}
#endregion
#region
/// <summary>
/// 转换人民币大小金额
/// </summary>
/// <param name="num">金额</param>
/// <returns>返回大写形式</returns>
public static string CmycurD(decimal num)
{
string str1 = "零壹贰叁肆伍陆柒捌玖"; //0-9所对应的汉字
string str2 = "万仟佰拾亿仟佰拾万仟佰拾元角分"; //数字位所对应的汉字
string str3 = ""; //从原num值中取出的值
string str4 = ""; //数字的字符串形式
string str5 = ""; //人民币大写金额形式
int i; //循环变量
int j; //num的值乘以100的字符串长度
string ch1 = ""; //数字的汉语读法
string ch2 = ""; //数字位的汉字读法
int nzero = 0; //用来计算连续的零值是几个
int temp; //从原num值中取出的值
num = Math.Round(Math.Abs(num), 2); //将num取绝对值并四舍五入取2位小数
str4 = ((long)(num * 100)).ToString(); //将num乘100并转换成字符串形式
j = str4.Length; //找出最高位
if (j > 15) { return "溢出"; }
str2 = str2.Substring(15 - j); //取出对应位数的str2的值。如200.55,j为5所以str2=佰拾元角分
//循环取出每一位需要转换的值
for (i = 0; i < j; i++)
{
str3 = str4.Substring(i, 1); //取出需转换的某一位的值
temp = Convert.ToInt32(str3); //转换为数字
if (i != (j - 3) && i != (j - 7) && i != (j - 11) && i != (j - 15))
{
//当所取位数不为元、万、亿、万亿上的数字时
if (str3 == "0")
{
ch1 = "";
ch2 = "";
nzero = nzero + 1;
}
else
{
if (str3 != "0" && nzero != 0)
{
ch1 = "零" + str1.Substring(temp * 1, 1);
ch2 = str2.Substring(i, 1);
nzero = 0;
}
else
{
ch1 = str1.Substring(temp * 1, 1);
ch2 = str2.Substring(i, 1);
nzero = 0;
}
}
}
else
{
//该位是万亿,亿,万,元位等关键位
if (str3 != "0" && nzero != 0)
{
ch1 = "零" + str1.Substring(temp * 1, 1);
ch2 = str2.Substring(i, 1);
nzero = 0;
}
else
{
if (str3 != "0" && nzero == 0)
{
ch1 = str1.Substring(temp * 1, 1);
ch2 = str2.Substring(i, 1);
nzero = 0;
}
else
{
if (str3 == "0" && nzero >= 3)
{
ch1 = "";
ch2 = "";
nzero = nzero + 1;
}
else
{
if (j >= 11)
{
ch1 = "";
nzero = nzero + 1;
}
else
{
ch1 = "";
ch2 = str2.Substring(i, 1);
nzero = nzero + 1;
}
}
}
}
}
if (i == (j - 11) || i == (j - 3))
{
//如果该位是亿位或元位,则必须写上
ch2 = str2.Substring(i, 1);
}
str5 = str5 + ch1 + ch2;
if (i == j - 1 && str3 == "0")
{
//最后一位为0时加上“整”
str5 = str5 + '整';
}
}
if (num == 0)
{
str5 = "零元整";
}
return str5;
}
/**/
/// <summary>
/// 一个重载将字符串先转换成数字在调用CmycurD(decimal num)
/// </summary>
/// <param name="num">用户输入的金额字符串形式未转成decimal</param>
/// <returns></returns>
public static string CmycurD(string numstr)
{
try
{
decimal num = Convert.ToDecimal(numstr);
return CmycurD(num);
}
catch
{
return "非数字形式!";
}
}
#endregion
#region
/// <summary>
/// 数字转中文
/// </summary>
/// <param name="number">eg: 22</param>
/// <returns></returns>
public static string NumberToChinese(int number)
{
string res = string.Empty;
string str = number.ToString();
string schar = str.Substring(0, 1);
switch (schar)
{
case "1":
res = "一";
break;
case "2":
res = "二";
break;
case "3":
res = "三";
break;
case "4":
res = "四";
break;
case "5":
res = "五";
break;
case "6":
res = "六";
break;
case "7":
res = "七";
break;
case "8":
res = "八";
break;
case "9":
res = "九";
break;
default:
res = "零";
break;
}
if (str.Length > 1)
{
switch (str.Length)
{
case 2:
case 6:
res += "十";
break;
case 3:
case 7:
res += "百";
break;
case 4:
res += "千";
break;
case 5:
res += "万";
break;
default:
res += "";
break;
}
res += NumberToChinese(int.Parse(str.Substring(1, str.Length - 1)));
}
return res;
}
#endregion
}
}

View File

@@ -0,0 +1,87 @@
/********************************************************************
* *
* * Copyright (C) 2013-2018 uiskin.cn
* * 作者: BinGoo QQ315567586
* * 请尊重作者劳动成果,请保留以上作者信息,禁止用于商业活动。
* *
* * 创建时间2017-09-18
* * 说明Csv文件操作类
* *
********************************************************************/
using System.Data;
using System.IO;
using System.Text;
namespace NetWorkHelper.ITool
{
class CsvManager
{
/// <summary>
/// 导出报表为Csv
/// </summary>
/// <param name="dt">DataTable</param>
/// <param name="strFilePath">物理路径</param>
/// <param name="tableheader">表头</param>
/// <param name="columname">字段标题,逗号分隔</param>
public static bool DataTable2Csv(DataTable dt, string strFilePath, string tableheader, string columname)
{
try
{
string strBufferLine;
StreamWriter strmWriterObj = new StreamWriter(strFilePath, false, Encoding.UTF8);
strmWriterObj.WriteLine(tableheader);
strmWriterObj.WriteLine(columname);
for (int i = 0; i < dt.Rows.Count; i++)
{
strBufferLine = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
if (j > 0)
strBufferLine += ",";
strBufferLine += dt.Rows[i][j].ToString();
}
strmWriterObj.WriteLine(strBufferLine);
}
strmWriterObj.Close();
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 将Csv读入DataTable
/// </summary>
/// <param name="filePath">csv文件路径</param>
/// <param name="n">表示第n行是字段title,第n+1行是记录开始</param>
/// <param name="dataTable">要导出的dataTable</param>
public static DataTable Csv2Dt(string filePath, int n, DataTable dataTable)
{
StreamReader reader = new StreamReader(filePath, Encoding.UTF8, false);
int i, m = 0;
while (reader.Peek() > 0)
{
m = m + 1;
string str = reader.ReadLine();
if (string.IsNullOrEmpty(str))
{
break;
}
if (m >= n + 1)
{
string[] split = str.Split(',');
DataRow dr = dataTable.NewRow();
for (i = 0; i < split.Length; i++)
{
dr[i] = split[i];
}
dataTable.Rows.Add(dr);
}
}
return dataTable;
}
}
}

View File

@@ -0,0 +1,306 @@
/********************************************************************
* *
* * Copyright (C) 2013-2018 uiskin.cn
* * 作者: BinGoo QQ315567586
* * 请尊重作者劳动成果,请保留以上作者信息,禁止用于商业活动。
* *
* * 创建时间2017-09-18
* * 说明:时间操作类
* *
********************************************************************/
using System;
namespace NetWorkHelper.ITool
{
internal class DateTimeManager
{
/// <summary>
/// 返回每月的第一天和最后一天
/// </summary>
/// <param name="month"></param>
/// <param name="firstDay"></param>
/// <param name="lastDay"></param>
public static void ReturnDateFormat(int month, out string firstDay, out string lastDay)
{
int year = DateTime.Now.Year + month / 12;
if (month != 12)
{
month = month % 12;
}
switch (month)
{
case 1:
firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
lastDay = DateTime.Now.ToString(year + "-0" + month + "-31");
break;
case 2:
firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
if (DateTime.IsLeapYear(DateTime.Now.Year))
lastDay = DateTime.Now.ToString(year + "-0" + month + "-29");
else
lastDay = DateTime.Now.ToString(year + "-0" + month + "-28");
break;
case 3:
firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
lastDay = DateTime.Now.ToString("yyyy-0" + month + "-31");
break;
case 4:
firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
lastDay = DateTime.Now.ToString(year + "-0" + month + "-30");
break;
case 5:
firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
lastDay = DateTime.Now.ToString(year + "-0" + month + "-31");
break;
case 6:
firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
lastDay = DateTime.Now.ToString(year + "-0" + month + "-30");
break;
case 7:
firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
lastDay = DateTime.Now.ToString(year + "-0" + month + "-31");
break;
case 8:
firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
lastDay = DateTime.Now.ToString(year + "-0" + month + "-31");
break;
case 9:
firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
lastDay = DateTime.Now.ToString(year + "-0" + month + "-30");
break;
case 10:
firstDay = DateTime.Now.ToString(year + "-" + month + "-01");
lastDay = DateTime.Now.ToString(year + "-" + month + "-31");
break;
case 11:
firstDay = DateTime.Now.ToString(year + "-" + month + "-01");
lastDay = DateTime.Now.ToString(year + "-" + month + "-30");
break;
default:
firstDay = DateTime.Now.ToString(year + "-" + month + "-01");
lastDay = DateTime.Now.ToString(year + "-" + month + "-31");
break;
}
}
/// <summary>
/// 将时间格式化成 年月日 的形式,如果时间为null返回当前系统时间
/// </summary>
/// <param name="dt">年月日分隔符</param>
/// <param name="Separator"></param>
/// <returns></returns>
public string GetFormatDate(DateTime dt, char Separator)
{
if (dt != null && !dt.Equals(DBNull.Value))
{
string tem = string.Format("yyyy{0}MM{1}dd", Separator, Separator);
return dt.ToString(tem);
}
else
{
return GetFormatDate(DateTime.Now, Separator);
}
}
/// <summary>
/// 将时间格式化成 时分秒 的形式,如果时间为null返回当前系统时间
/// </summary>
/// <param name="dt"></param>
/// <param name="Separator"></param>
/// <returns></returns>
public string GetFormatTime(DateTime dt, char Separator)
{
if (dt != null && !dt.Equals(DBNull.Value))
{
string tem = string.Format("hh{0}mm{1}ss", Separator, Separator);
return dt.ToString(tem);
}
else
{
return GetFormatDate(DateTime.Now, Separator);
}
}
/// <summary>
/// 把秒转换成分钟
/// </summary>
/// <returns></returns>
public static int SecondToMinute(int Second)
{
decimal mm = (decimal)((decimal)Second / (decimal)60);
return Convert.ToInt32(Math.Ceiling(mm));
}
#region
/// <summary>
/// 返回某年某月最后一天
/// </summary>
/// <param name="year">年份</param>
/// <param name="month">月份</param>
/// <returns>日</returns>
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 string DateDiff(DateTime DateTime1, DateTime DateTime2)
{
string dateDiff = null;
try
{
//TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
//TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
//TimeSpan ts = ts1.Subtract(ts2).Duration();
TimeSpan ts = DateTime2 - DateTime1;
if (ts.Days >= 1)
{
dateDiff = string.Format("{0}月{1}日", DateTime1.Month, DateTime1.Day);
}
else
{
if (ts.Hours > 1)
{
dateDiff = string.Format("{0}小时前", ts.Hours);
}
else
{
dateDiff = string.Format("{0}分钟前", ts.Minutes);
}
}
}
catch
{
}
return dateDiff;
}
#endregion
#region
/// <summary>
/// 获得两个日期的间隔
/// </summary>
/// <param name="DateTime1">日期一。</param>
/// <param name="DateTime2">日期二。</param>
/// <returns>日期间隔TimeSpan。</returns>
public static TimeSpan DateDiff2(DateTime DateTime1, DateTime DateTime2)
{
TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
return ts;
}
#endregion
#region
/// <summary>
/// 格式化日期时间
/// </summary>
/// <param name="dateTime1">日期时间</param>
/// <param name="dateMode">显示模式</param>
/// <returns>0-9种模式的日期</returns>
public static string FormatDate(DateTime dateTime1, string dateMode)
{
switch (dateMode)
{
case "0":
return dateTime1.ToString("yyyy-MM-dd");
case "1":
return dateTime1.ToString("yyyy-MM-dd HH:mm:ss");
case "2":
return dateTime1.ToString("yyyy/MM/dd");
case "3":
return dateTime1.ToString("yyyy年MM月dd日");
case "4":
return dateTime1.ToString("MM-dd");
case "5":
return dateTime1.ToString("MM/dd");
case "6":
return dateTime1.ToString("MM月dd日");
case "7":
return dateTime1.ToString("yyyy-MM");
case "8":
return dateTime1.ToString("yyyy/MM");
case "9":
return dateTime1.ToString("yyyy年MM月");
default:
return dateTime1.ToString();
}
}
#endregion
#region
/// <summary>
/// 得到随机日期
/// </summary>
/// <param name="time1">起始日期</param>
/// <param name="time2">结束日期</param>
/// <returns>间隔日期之间的 随机日期</returns>
public static DateTime GetRandomTime(DateTime time1, DateTime time2)
{
Random random = new Random();
DateTime minTime = new DateTime();
DateTime maxTime = new DateTime();
TimeSpan ts = new TimeSpan(time1.Ticks - time2.Ticks);
// 获取两个时间相隔的秒数
double dTotalSecontds = ts.TotalSeconds;
int iTotalSecontds = 0;
if (dTotalSecontds > Int32.MaxValue)
{
iTotalSecontds = Int32.MaxValue;
}
else if (dTotalSecontds < Int32.MinValue)
{
iTotalSecontds = Int32.MinValue;
}
else
{
iTotalSecontds = (int)dTotalSecontds;
}
if (iTotalSecontds > 0)
{
minTime = time2;
maxTime = time1;
}
else if (iTotalSecontds < 0)
{
minTime = time1;
maxTime = time2;
}
else
{
return time1;
}
int maxValue = iTotalSecontds;
if (iTotalSecontds <= Int32.MinValue)
maxValue = Int32.MinValue + 1;
int i = random.Next(Math.Abs(maxValue));
return minTime.AddSeconds(i);
}
#endregion
}
}

View File

@@ -0,0 +1,328 @@
/********************************************************************
* *
* * Copyright (C) 2013-2018 uiskin.cn
* * 作者: BinGoo QQ315567586
* * 请尊重作者劳动成果,请保留以上作者信息,禁止用于商业活动。
* *
* * 创建时间2017-09-18
* * 说明JSON操作类
* *
********************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Reflection;
using System.Text;
namespace NetWorkHelper.ITool
{
public class JsonManager
{
/// <summary>
/// 过滤特殊字符
/// </summary>
private static string String2Json(string s)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
char c = s.ToCharArray()[i];
switch (c)
{
case '\"':
sb.Append("\\\""); break;
case '\\':
sb.Append("\\\\"); break;
case '/':
sb.Append("\\/"); break;
case '\b':
sb.Append("\\b"); break;
case '\f':
sb.Append("\\f"); break;
case '\n':
sb.Append("\\n"); break;
case '\r':
sb.Append("\\r"); break;
case '\t':
sb.Append("\\t"); break;
default:
sb.Append(c); break;
}
}
return sb.ToString();
}
/// <summary>
/// 格式化字符型、日期型、布尔型
/// </summary>
private static string StringFormat(string str, Type type)
{
if (type == typeof(string))
{
str = String2Json(str);
str = "\"" + str + "\"";
}
else if (type == typeof(DateTime))
{
str = "\"" + str + "\"";
}
else if (type == typeof(bool))
{
str = str.ToLower();
}
else if (type != typeof(string) && string.IsNullOrEmpty(str))
{
str = "\"" + str + "\"";
}
return str;
}
#region List转换成Json
/// <summary>
/// List转换成Json
/// </summary>
public static string ListToJson<T>(IList<T> list)
{
object obj = list[0];
return ListToJson<T>(list, obj.GetType().Name);
}
/// <summary>
/// List转换成Json
/// </summary>
public static string ListToJson<T>(IList<T> list, string jsonName)
{
StringBuilder Json = new StringBuilder();
if (string.IsNullOrEmpty(jsonName)) jsonName = list[0].GetType().Name;
Json.Append("{\"" + jsonName + "\":[");
if (list.Count > 0)
{
for (int i = 0; i < list.Count; i++)
{
T obj = Activator.CreateInstance<T>();
PropertyInfo[] pi = obj.GetType().GetProperties();
Json.Append("{");
for (int j = 0; j < pi.Length; j++)
{
Type type = pi[j].GetValue(list[i], null).GetType();
Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));
if (j < pi.Length - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < list.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
}
#endregion
#region Json
/// <summary>
/// 对象转换为Json
/// </summary>
/// <param name="jsonObject">对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(object jsonObject)
{
string jsonString = "{";
PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
for (int i = 0; i < propertyInfo.Length; i++)
{
object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
string value = string.Empty;
if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
{
value = "'" + objectValue.ToString() + "'";
}
else if (objectValue is string)
{
value = "'" + ToJson(objectValue.ToString()) + "'";
}
else if (objectValue is IEnumerable)
{
value = ToJson((IEnumerable)objectValue);
}
else
{
value = ToJson(objectValue.ToString());
}
jsonString += "\"" + ToJson(propertyInfo[i].Name) + "\":" + value + ",";
}
jsonString.Remove(jsonString.Length - 1, jsonString.Length);
return jsonString + "}";
}
#endregion
#region Json
/// <summary>
/// 对象集合转换Json
/// </summary>
/// <param name="array">集合对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(IEnumerable array)
{
string jsonString = "[";
foreach (object item in array)
{
jsonString += ToJson(item) + ",";
}
jsonString.Remove(jsonString.Length - 1, jsonString.Length);
return jsonString + "]";
}
#endregion
#region Json
/// <summary>
/// 普通集合转换Json
/// </summary>
/// <param name="array">集合对象</param>
/// <returns>Json字符串</returns>
public static string ToArrayString(IEnumerable array)
{
string jsonString = "[";
foreach (object item in array)
{
jsonString = ToJson(item.ToString()) + ",";
}
jsonString.Remove(jsonString.Length - 1, jsonString.Length);
return jsonString + "]";
}
#endregion
#region DataSet转换为Json
/// <summary>
/// DataSet转换为Json
/// </summary>
/// <param name="dataSet">DataSet对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(DataSet dataSet)
{
string jsonString = "{";
foreach (DataTable table in dataSet.Tables)
{
jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
}
jsonString = jsonString.TrimEnd(',');
return jsonString + "}";
}
#endregion
#region Datatable转换为Json
/// <summary>
/// Datatable转换为Json
/// </summary>
/// <param name="table">Datatable对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(DataTable dt)
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("[");
DataRowCollection drc = dt.Rows;
for (int i = 0; i < drc.Count; i++)
{
jsonString.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
string strKey = dt.Columns[j].ColumnName;
string strValue = drc[i][j].ToString();
Type type = dt.Columns[j].DataType;
jsonString.Append("\"" + strKey + "\":");
strValue = StringFormat(strValue, type);
if (j < dt.Columns.Count - 1)
{
jsonString.Append(strValue + ",");
}
else
{
jsonString.Append(strValue);
}
}
jsonString.Append("},");
}
jsonString.Remove(jsonString.Length - 1, 1);
jsonString.Append("]");
return jsonString.ToString();
}
/// <summary>
/// DataTable转换为Json
/// </summary>
public static string ToJson(DataTable dt, string jsonName)
{
StringBuilder Json = new StringBuilder();
if (string.IsNullOrEmpty(jsonName)) jsonName = dt.TableName;
Json.Append("{\"" + jsonName + "\":[");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Json.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
Type type = dt.Rows[i][j].GetType();
Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));
if (j < dt.Columns.Count - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < dt.Rows.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
}
#endregion
#region DataReader转换为Json
/// <summary>
/// DataReader转换为Json
/// </summary>
/// <param name="dataReader">DataReader对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(DbDataReader dataReader)
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("[");
while (dataReader.Read())
{
jsonString.Append("{");
for (int i = 0; i < dataReader.FieldCount; i++)
{
Type type = dataReader.GetFieldType(i);
string strKey = dataReader.GetName(i);
string strValue = dataReader[i].ToString();
jsonString.Append("\"" + strKey + "\":");
strValue = StringFormat(strValue, type);
if (i < dataReader.FieldCount - 1)
{
jsonString.Append(strValue + ",");
}
else
{
jsonString.Append(strValue);
}
}
jsonString.Append("},");
}
dataReader.Close();
jsonString.Remove(jsonString.Length - 1, 1);
jsonString.Append("]");
return jsonString.ToString();
}
#endregion
}
}

View File

@@ -0,0 +1,87 @@
/********************************************************************
* *
* * Copyright (C) 2013-? Corporation All rights reserved.
* * 作者: BinGoo QQ315567586
* * 请尊重作者劳动成果,请保留以上作者信息,禁止用于商业活动。
* *
* * 创建时间2014-08-05
* * 说明:自定义枚举文件
* *
********************************************************************/
namespace NetWorkHelper.IUser
{
/// <summary>
/// 停车位状态
/// </summary>
public enum SitState
{
None,
Enter,
Leave,
On,
Out
}
/// <summary>
/// 车辆运动状态
/// </summary>
public enum VehicleMotionState
{
/// <summary>
/// 运动
/// </summary>
Running = 0x01,
/// <summary>
/// 停止
/// </summary>
Stop = 0x00,
/// <summary>
/// 加速
/// </summary>
AddSpeed = 0x02,
/// <summary>
/// 减速
/// </summary>
DelSpeed = 0x03,
}
/// <summary>
/// 信号灯状态
/// </summary>
public enum LedState
{
/// <summary>
/// 绿灯
/// </summary>
Green = 0x00,
/// <summary>
/// 绿灯
/// </summary>
GreenFlash = 0x01,
/// <summary>
/// 红灯
/// </summary>
Red = 0x02,
/// <summary>
/// 黄灯
/// </summary>
Yellow = 0x04,
/// <summary>
/// 黄闪
/// </summary>
YellowFlash = 0x05,
/// <summary>
/// 无灯色(灭灯)
/// </summary>
None = 0x06
}
}

View File

@@ -0,0 +1,188 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{FB7970FD-F699-4093-83D0-509501B7863C}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>NetWorkHelper</RootNamespace>
<AssemblyName>NetWorkHelper</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>AnyCPU</PlatformTarget>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Office.Interop.Excel, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Office.Interop.Excel.15.0.4795.1001\lib\net20\Microsoft.Office.Interop.Excel.dll</HintPath>
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Runtime.Serialization.Formatters.Soap" />
<Reference Include="System.Web" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Addins\NetAddinManagement.cs" />
<Compile Include="Addins\AddinUtil.cs" />
<Compile Include="Addins\IAddin.cs" />
<Compile Include="Addins\IAddinManager.cs" />
<Compile Include="Helper\ApplicationHelper.cs" />
<Compile Include="Helper\CollectionHelper.cs" />
<Compile Include="Helper\DataFrame.cs" />
<Compile Include="Helper\DataFrameHeader.cs" />
<Compile Include="Helper\FileHelper.cs" />
<Compile Include="Helper\ReflectionHelper.cs" />
<Compile Include="Helper\TypeHelper.cs" />
<Compile Include="Helper\WindowsHelper.cs" />
<Compile Include="Helper\XmlHelper.cs" />
<Compile Include="IBase\MapItem.cs" />
<Compile Include="ICollections\CollectionConverter.cs" />
<Compile Include="ICollections\SortedArray.cs" />
<Compile Include="ICommond\CommonMethod.cs" />
<Compile Include="ICommond\IDelegate.cs" />
<Compile Include="ITool\ConvertStringManager.cs" />
<Compile Include="IModels\IClient.cs" />
<Compile Include="ITool\CsvManager.cs" />
<Compile Include="ITool\DateTimeManager.cs" />
<Compile Include="ITool\JsonManager.cs" />
<Compile Include="IUser\CustomEnum.cs" />
<Compile Include="TClass\ClientType.cs" />
<Compile Include="TClass\ControlTag.cs" />
<Compile Include="Helper\ImageHelper.cs" />
<Compile Include="TCP\IBase.cs" />
<Compile Include="TCP\ITcpClient.cs">
<SubType>Component</SubType>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Compile>
<Compile Include="TCP\ITcpClient.Designer.cs">
<DependentUpon>ITcpClient.cs</DependentUpon>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Compile>
<Compile Include="TCP\ITcpServer.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="TCP\ITcpServer.Designer.cs">
<DependentUpon>ITcpServer.cs</DependentUpon>
</Compile>
<Compile Include="UDP\AxUdpClient.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="UDP\AxUdpClient.Designer.cs">
<DependentUpon>AxUdpClient.cs</DependentUpon>
</Compile>
<Compile Include="Helper\MD5Helper.cs" />
<Compile Include="UDP\Controls\ControlState.cs" />
<Compile Include="UDP\Controls\FileTansfersContainer.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="UDP\Controls\FileTransfersItem.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="UDP\Controls\FileTransfersItemStyle.cs" />
<Compile Include="UDP\Controls\FileTransfersItemText.cs" />
<Compile Include="UDP\Controls\GraphicsPathHelper.cs" />
<Compile Include="UDP\Controls\IFileTransfersItemText.cs" />
<Compile Include="UDP\Controls\RoundStyle.cs" />
<Compile Include="UDP\Controls\TraFransfersFile.cs" />
<Compile Include="UDP\Controls\TraFransfersFileStart.cs" />
<Compile Include="UDP\Event\ReadFileBufferEvent.cs" />
<Compile Include="UDP\Event\ReceiveDataEvent.cs" />
<Compile Include="UDP\Event\FileReceiveBufferEvent.cs" />
<Compile Include="UDP\Event\FileReceiveCompleteEvent.cs" />
<Compile Include="UDP\Event\FileReceiveEvent.cs" />
<Compile Include="UDP\Event\FileSendBufferEvent.cs" />
<Compile Include="UDP\Event\FileSendEvent.cs" />
<Compile Include="UDP\Event\RequestSendFileEvent.cs" />
<Compile Include="UDP\Receive\ReadFileObject.cs" />
<Compile Include="UDP\Receive\ReceiveFileManager.cs" />
<Compile Include="UDP\Send\SendFileManager.cs" />
<Compile Include="Helper\SerHelper.cs" />
<Compile Include="UDP\IDataCell.cs" />
<Compile Include="UDP\SerializableClass\MsgCell.cs" />
<Compile Include="UDP\SerializableClass\MsgTypeCell.cs" />
<Compile Include="UDP\SerializableClass\ResponeTraFransfersFile.cs" />
<Compile Include="UDP\UdpLibrary.cs" />
<Compile Include="TClass\EnumClass.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="UDP\AxUdpClient.resx">
<DependentUpon>AxUdpClient.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Folder Include="IFile\" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,35 @@
using System.Reflection;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("NetWorkHelper包含Net基础操作类Socket高度组件封装类库")]
[assembly: AssemblyDescription("作者BinGoo ; QQ:315567586")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("BinGoo")]
[assembly: AssemblyProduct("NetWorkHelper")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("BinGoo")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("0bbfb4a9-e262-4bbc-a53c-bd61b56c7cf9")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("4.18.04.25")]
[assembly: AssemblyFileVersion("4.18.04.25")]

View File

@@ -0,0 +1,36 @@
namespace SocketHelper
{
partial class AxTcpClient
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

View File

@@ -0,0 +1,416 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace SocketHelper
{
public partial class AxTcpClient : Component
{
#region
public AxTcpClient()
{
InitializeComponent();
}
public AxTcpClient(IContainer container)
{
container.Add(this);
InitializeComponent();
}
#endregion
#region
/// <summary>
/// 服务端IP
/// </summary>
private string _serverip;
[Description("服务端IP")]
[Category("TcpClient属性")]
public string ServerIp
{
set { _serverip = value; }
get { return _serverip; }
}
/// <summary>
/// 服务端监听端口
/// </summary>
private int _serverport;
[Description("服务端监听端口")]
[Category("TcpClient属性")]
public int ServerPort
{
set { _serverport = value; }
get { return _serverport; }
}
/// <summary>
/// TcpClient客户端
/// </summary>
private TcpClient _tcpclient = null;
[Description("TcpClient操作类")]
[Category("TcpClient隐藏属性")]
[Browsable(false)]
public TcpClient Tcpclient
{
set { _tcpclient = value; }
get { return _tcpclient; }
}
/// <summary>
/// Tcp客户端连接线程
/// </summary>
private Thread _tcpthread = null;
[Description("TcpClient连接服务端线程")]
[Category("TcpClient隐藏属性")]
[Browsable(false)]
public Thread Tcpthread
{
set { _tcpthread = value; }
get { return _tcpthread; }
}
/// <summary>
/// 是否启动Tcp连接线程
/// </summary>
private bool _isStarttcpthreading = false;
[Description("是否启动Tcp连接线程")]
[Category("TcpClient隐藏属性")]
[Browsable(false)]
public bool IsStartTcpthreading
{
set { _isStarttcpthreading = value; }
get { return _isStarttcpthreading; }
}
/// <summary>
/// 是否启动TCP
/// </summary>
public bool IsStart = false;
/// <summary>
/// 是否重连
/// </summary>
private bool _isreconnection = false;
/// <summary>
/// 是否重连
/// </summary>
[Description("是否重连")]
[Category("TcpClient属性")]
public bool IsReconnection
{
set { _isreconnection = value; }
get { return _isreconnection; }
}
private int _reConnectionTime = 3000;
/// <summary>
/// 设置断开重连时间间隔单位毫秒默认3000毫秒
/// </summary>
[Description("设置断开重连时间间隔单位毫秒默认3000毫秒")]
[Category("TcpClient属性")]
public int ReConnectionTime
{
get { return _reConnectionTime; }
set { _reConnectionTime = value; }
}
private string _receivestr;
/// <summary>
/// 接收Socket数据包 缓存字符串
/// </summary>
[Description("接收Socket数据包 缓存字符串")]
[Category("TcpClient隐藏属性"), Browsable(false)]
public string Receivestr
{
set { _receivestr = value; }
get { return _receivestr; }
}
/// <summary>
/// 重连次数
/// </summary>
private int _reConectedCount = 0;
[Description("重连次数")]
[Category("TcpClient隐藏属性"), Browsable(false)]
public int ReConectedCount
{
get { return _reConectedCount; }
set { _reConectedCount = value; }
}
#endregion
#region
/// <summary>
/// 启动连接Socket服务器
/// </summary>
public void StartConnection()
{
try
{
IsStart = true;
IsReconnection = true;
CreateTcpClient();
}
catch (Exception ex)
{
OnTcpClientErrorMsgEnterHead("错误信息:" + ex.Message);
}
}
/// <summary>
/// 创建线程连接
/// </summary>
private void CreateTcpClient()
{
//如果已经启动TCP并且是可重连状态则继续连接
if (!(IsReconnection && IsStart))
return;
//标示已启动连接,防止重复启动线程
IsReconnection = false;
IsStartTcpthreading = true;
Tcpclient = new TcpClient();
Tcpthread = new Thread(StartTcpThread);
IsOnlienCheckStart();
Tcpthread.Start();
}
/// <summary>
/// 线程接收Socket上传的数据
/// </summary>
private void StartTcpThread()
{
byte[] receivebyte = new byte[2048];
int bytelen;
try
{
while (IsStartTcpthreading)
{
#region
if (!Tcpclient.Connected)
{
try
{
if (ReConectedCount != 0)
{
//返回状态信息
OnTcpClientStateInfoEnterHead(
string.Format("正在第{0}次重新连接服务器... ...", ReConectedCount),
SocketState.Reconnection);
}
else
{
//SocketStateInfo
OnTcpClientStateInfoEnterHead("正在连接服务器... ...", SocketState.Connecting);
}
Tcpclient.Connect(IPAddress.Parse(ServerIp), ServerPort);
OnTcpClientStateInfoEnterHead("已连接服务器", SocketState.Connected);
//Tcpclient.Client.Send(Encoding.Default.GetBytes("login"));
}
catch
{
//连接失败
ReConectedCount++;
//强制重新连接
IsReconnection = true;
IsStartTcpthreading = false;
//每三秒重连一次
Thread.Sleep(ReConnectionTime);
continue;
}
}
//Tcpclient.Client.Send(Encoding.Default.GetBytes("login"));
bytelen = Tcpclient.Client.Receive(receivebyte);
// 连接断开
if (bytelen == 0)
{
//返回状态信息
OnTcpClientStateInfoEnterHead("与服务器断开连接... ...", SocketState.Disconnect);
// 异常退出、强制重新连接
IsReconnection = true;
ReConectedCount = 1;
IsStartTcpthreading = false;
continue;
}
Receivestr = ASCIIEncoding.Default.GetString(receivebyte, 0, bytelen);
byte[] bytes = new byte[bytelen];
Array.Copy(receivebyte, 0, bytes, 0, bytelen);
//OnTcpClientRecevice(bytes);
if (Receivestr.Trim() != "")
{
//接收数据
try
{
OnTcpClientRecevice(Receivestr, bytes);
}
catch (Exception ex)
{
//返回错误信息
OnTcpClientErrorMsgEnterHead("错误信息:" + ex.Message);
}
}
#endregion
}
//此时线程将结束,人为结束,自动判断是否重连
IsReconnection = true;
CreateTcpClient();
}
catch (Exception ex)
{
IsReconnection = true;
CreateTcpClient();
//返回错误信息
try
{
OnTcpClientErrorMsgEnterHead("错误信息:" + ex.Message);
}
catch { }
}
}
/// <summary>
/// 断开连接
/// </summary>
public void StopConnection()
{
IsStart = false;
IsReconnection = false;
IsStartTcpthreading = false;
Thread.Sleep(10);
if (Tcpclient != null)
{
//关闭连接
Tcpclient.Close();
}
if (Tcpthread != null)
{
Tcpthread.Interrupt();
//关闭线程
Tcpthread.Abort();
//Tcpthread = null;
}
OnTcpClientStateInfoEnterHead("断开连接", SocketState.Disconnect);
//标示线程已关闭可以重新连接
}
/// <summary>
/// 发送Socket文本消息
/// </summary>
/// <param name="cmdstr"></param>
public void SendCommand(string cmdstr)
{
try
{
//byte[] _out=Encoding.GetEncoding("GBK").GetBytes(cmdstr);
byte[] _out = Encoding.Default.GetBytes(cmdstr);
Tcpclient.Client.Send(_out);
}
catch (Exception ex)
{
//返回错误信息
OnTcpClientErrorMsgEnterHead(ex.Message);
}
}
public void SendFile(string filename)
{
Tcpclient.Client.BeginSendFile(filename,
new AsyncCallback(SendCallback), Tcpclient);
//Tcpclient.Client.SendFile(filename);
}
private void SendCallback(IAsyncResult result)
{
try
{
TcpClient tc = (TcpClient)result.AsyncState;
// Complete sending the data to the remote device.
tc.Client.EndSendFile(result);
}
catch (SocketException ex)
{
}
}
/// <summary>
/// 发送Socket消息
/// </summary>
/// <param name="byteMsg"></param>
public void SendCommand(byte[] byteMsg)
{
try
{
Tcpclient.Client.Send(byteMsg);
}
catch (Exception ex)
{
//返回错误信息
OnTcpClientErrorMsgEnterHead("错误信息:" + ex.Message);
}
}
// 检查一个Socket是否可连接
public bool IsOnline()
{
return !((Tcpclient.Client.Poll(1000, SelectMode.SelectRead) && (Tcpclient.Client.Available == 0)) || !Tcpclient.Client.Connected);
}
public void IsOnlienCheckThread()
{
while (IsReconnection)
{
if (IsOnline())
{
IsStartTcpthreading = false;
}
}
}
public void IsOnlienCheckStart()
{
Thread t = new Thread(new ThreadStart(IsOnlienCheckThread));
t.Start();
}
#endregion
#region
#region OnRecevice接收数据事件
public delegate void ReceviceEventHandler(string msg, byte[] data);
[Description("接收数据事件")]
[Category("TcpClient事件")]
public event ReceviceEventHandler OnRecevice;
protected virtual void OnTcpClientRecevice(string msg, byte[] data)
{
if (OnRecevice != null)
OnRecevice(msg, data);
}
#endregion
#region OnErrorMsg返回错误消息事件
public delegate void ErrorMsgEventHandler(string msg);
[Description("返回错误消息事件")]
[Category("TcpClient事件")]
public event ErrorMsgEventHandler OnErrorMsg;
protected virtual void OnTcpClientErrorMsgEnterHead(string msg)
{
if (OnErrorMsg != null)
OnErrorMsg(msg);
}
#endregion
#region OnStateInfo连接状态改变时返回连接状态事件
public delegate void StateInfoEventHandler(string msg, SocketState state);
[Description("连接状态改变时返回连接状态事件")]
[Category("TcpClient事件")]
public event StateInfoEventHandler OnStateInfo;
protected virtual void OnTcpClientStateInfoEnterHead(string msg, SocketState state)
{
if (OnStateInfo != null)
OnStateInfo(msg, state);
}
#endregion
#endregion
}
}

View File

@@ -0,0 +1,36 @@
namespace SocketHelper
{
partial class AxTcpServer
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,36 @@
namespace SocketHelper.TCP
{
partial class AxTcpWebClient
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
namespace SocketHelper.TCP
{
public partial class AxTcpWebClient : Component
{
public AxTcpWebClient()
{
InitializeComponent();
}
public AxTcpWebClient(IContainer container)
{
container.Add(this);
InitializeComponent();
}
}
}

View File

@@ -0,0 +1,24 @@
/********************************************************************
* *
* * Copyright (C) 2013-2018 uiskin.cn
* * 作者: BinGoo QQ315567586
* * 请尊重作者劳动成果,请保留以上作者信息,禁止用于商业活动。
* *
* * 创建时间2014-08-05
* * 说明ITcp组件的基类
* *
********************************************************************/
namespace NetWorkHelper.TCP
{
interface IServerBase
{
/// <summary>
/// 启动
/// </summary>
void Start();
/// <summary>
/// 停止
/// </summary>
void Stop();
}
}

View File

@@ -0,0 +1,36 @@
namespace NetWorkHelper.TCP
{
partial class ITcpClient
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

View File

@@ -0,0 +1,624 @@
using NetWorkHelper.ICommond;
using NetWorkHelper.IModels;
using System;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace NetWorkHelper.TCP
{
public partial class ITcpClient : Component
{
//#region 读取ini文件
//[DllImport("kernel32")]
//private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
///// <summary>
///// 读出INI文件
///// </summary>
///// <param name="Section">项目名称(如 [TypeName] )</param>
///// <param name="Key">键</param>
//public string IniReadValue(string Section, string Key)
//{
// StringBuilder temp = new StringBuilder(500);
// int i = GetPrivateProfileString(Section, Key, "", temp, 500, System.AppDomain.CurrentDomain.BaseDirectory + "MESConfig.ini");
// return temp.ToString();
//}
static int connecttimeout = 4000;
static int receivetimeout = 2000;
//static int sleeptime;
static int timeoutsend = 3;
//public void ReadINI()
//{
// //string dialog;
// //dialog = System.AppDomain.CurrentDomain.BaseDirectory + "MESConfig.ini";
// //ControlINI mesconfig = new ControlINI(dialog);
// //连接设置
// connecttimeout = Convert.ToInt32(IniReadValue("MESConfig", "connectTimeout")); ;
// receivetimeout = Convert.ToInt32(IniReadValue("MESConfig", "receiveTimeout"));
// _reConnectTime = Convert.ToInt32(IniReadValue("MESConfig", "sleepTime"));
// timeoutsend = Convert.ToInt32(IniReadValue("MESConfig", "timeoutSend"))+1;
//}
//#endregion
#region
public ITcpClient()
{
//ReadINI();
InitializeComponent();
}
public ITcpClient(IContainer container)
{
container.Add(this);
InitializeComponent();
}
#endregion
#region
public IClient Client = null;
private Thread _startThread = null;
private int _reConnectCount = 0;//重连计数
private int _maxConnectCount => timeoutsend;
private ConncetType _conncetType = ConncetType.Conncet;
private bool _isReconnect = true;//是否开启断开重连
private int _reConnectTime;//重连间隔时间
private bool _isStart = false;// 是否启动
private System.Timers.Timer _timer = new System.Timers.Timer(); // 连接后两秒未成功重连
//bool timeoutreconnected=true;//连接超时的重连
//bool datareconnected = true;//接收不到心跳包的重连
#endregion
#region
/// <summary>
/// 服务端IP
/// </summary>
private string _serverip = "127.0.0.1";
[Description("服务端IP")]
[Category("TCP客户端")]
public string ServerIp
{
set { _serverip = value; }
get { return _serverip; }
}
/// <summary>
/// 服务端监听端口
/// </summary>
private int _serverport = 5000;
[Description("服务端监听端口")]
[Category("TCP客户端")]
public int ServerPort
{
set { _serverport = value; }
get { return _serverport; }
}
/// <summary>
/// 网络端点
/// </summary>
private IPEndPoint _ipEndPoint = null;
[Description("网络端点,IP+PORT")]
[Category("TCP客户端")]
internal IPEndPoint IpEndPoint
{
get
{
try
{
IPAddress ipAddress = null;
ipAddress = string.IsNullOrEmpty(ServerIp)
? IPAddress.Any
: IPAddress.Parse(CommonMethod.HostnameToIp(ServerIp));
_ipEndPoint = new IPEndPoint(ipAddress, ServerPort);
}
catch
{
}
return _ipEndPoint;
}
}
/// <summary>
/// 是否重连
/// </summary>
[Description("是否重连")]
[Category("TCP客户端")]
public bool IsReconnection
{
set { _isReconnect = value; }
get { return _isReconnect; }
}
/// <summary>
/// 设置断开重连时间间隔单位毫秒默认3000毫秒
/// </summary>
[Description("设置断开重连时间间隔单位毫秒默认3000毫秒")]
[Category("TCP客户端")]
public int ReConnectionTime
{
get { return _reConnectTime; }
set { _reConnectTime = value; }
}
[Description("设置断开重连时间间隔单位毫秒默认3000毫秒")]
[Category("TCP客户端"), Browsable(false)]
public bool IsStart
{
get { return _isStart; }
set { _isStart = value; }
}
#endregion
#region
private readonly object _threadLock = new object();
public void StartConnect()
{
if (IsStart)
return;
lock (_threadLock)
{
if (_startThread == null || !_startThread.IsAlive)
{
_startThread = new Thread(StartThread);
_startThread.IsBackground = true;
_startThread.Start();
}
}
}
/// <summary>
/// 启动客户端基础的一个线程
/// </summary>
private void StartThread()
{
if (_conncetType == ConncetType.ReConncet && IsReconnection && !IsStart) //如果是重连的延迟N秒
{
Thread.Sleep(ReConnectionTime);
if (IsReconnection)
{
TcpClientStateInfo(string.Format("正在重连..."), SocketState.Reconnection);
}
try
{
_timer.Interval = connecttimeout;
_timer.Elapsed += Timer_Elapsed;
_timer.AutoReset = false;
_timer.Start();
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.ReceiveTimeout = receivetimeout;
socket.SendTimeout = 1000;
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true);
socket.BeginConnect(IpEndPoint, new AsyncCallback(AcceptCallback), socket);
//timeoutreconnected = true;//连接超时的重连
//datareconnected = true;//接收不到心跳包的重连
}
catch (Exception ex)
{
_timer.Stop();
TcpClientErrorMsg(string.Format("连接服务器失败,错误原因:{0},行号{1}", ex.Message, ex.StackTrace));
if (IsReconnection)
{
Reconnect();
}
}
}
else if (!IsStart)
{
if (IsReconnection)
{
TcpClientStateInfo("正在连接服务器... ...", SocketState.Connecting);
try
{
_timer.Interval = connecttimeout;
_timer.Elapsed += Timer_Elapsed;
_timer.AutoReset = false;
_timer.Start();
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.ReceiveTimeout = receivetimeout;
socket.SendTimeout = 1000;
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true);
socket.BeginConnect(IpEndPoint, new AsyncCallback(AcceptCallback), socket);
//timeoutreconnected = true;//连接超时的重连
//datareconnected = true;//接收不到心跳包的重连
}
catch (Exception ex)
{
_timer.Stop();
TcpClientErrorMsg(string.Format("连接服务器失败,错误原因:{0},行号{1}", ex.Message, ex.StackTrace));
if (IsReconnection)
{
Reconnect();
}
}
}
}
}
//连接超时则重新连接
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (IsReconnection)
{
//datareconnected = false;//接收不到心跳包的重连
TcpClientErrorMsg(string.Format("连接服务器失败"));
//if (Client != null)
//{
// ShutdownClient(Client);
// Client.WorkSocket.Close();
//}
Reconnect();
//reconnected = false;
}
}
/// <summary>
/// 当连接服务器之后的回调函数
/// </summary>
/// <param name="ar">TcpClient</param>
private void AcceptCallback(IAsyncResult ar)
{
_timer.Stop();
try
{
IsStart = true;
Socket socket = (Socket)ar.AsyncState;
socket.EndConnect(ar);
Client = new IClient(socket);
Client.WorkSocket.BeginReceive(Client.BufferInfo.ReceivedBuffer, 0, Client.BufferInfo.ReceivedBuffer.Length, 0, new AsyncCallback(ReadCallback), Client);
_conncetType = ConncetType.Conncet;
TcpClientStateInfo(string.Format("已连接服务器"), SocketState.Connected);
_reConnectCount = 0;
//timeoutreconnected = false;//连接超时的重连
//datareconnected = false;//接收不到心跳包的重连
}
catch (SocketException ex)
{
IsStart = false;
string msg = ex.Message;
if (ex.NativeErrorCode.Equals(10060))
{
//无法连接目标主机
msg = string.Format("{0} 无法连接: error code {1}!", "", ex.NativeErrorCode);
}
else if (ex.NativeErrorCode.Equals(10061))
{
msg = string.Format("{0} 主动拒绝正在重连: error code {1}!", "", ex.NativeErrorCode);
}
else if (ex.NativeErrorCode.Equals(10053))
{
//读写时主机断开
msg = string.Format("{0} 主动断开连接: error code {1}! ", "", ex.NativeErrorCode);
}
else
{
//其他错误
msg = string.Format("Disconnected: error code {0}!", ex.NativeErrorCode);
}
if (IsReconnection)
{
TcpClientErrorMsg(string.Format("连接服务器失败,错误原因:{0}", msg));
Reconnect();
}
}
catch (Exception ex)
{
}
}
#endregion
#region
/// <summary>
/// 重连模块
/// </summary>
private void Reconnect()
{
if (Client != null)
{
ShutdownClient(Client);
Client?.WorkSocket?.Close();
Client = null;
}
if (_conncetType == ConncetType.Conncet)
{
TcpClientStateInfo(string.Format("已断开服务器{0}", IsReconnection ? ",准备重连" : ""), SocketState.Disconnect);
}
if (!IsReconnection)
{
return;
}
_reConnectCount++;//每重连一次重连的次数加1
if (_conncetType == ConncetType.Conncet)
{
_conncetType = ConncetType.ReConncet;
//CommonMethod.EventInvoket(() => { ReconnectionStart(); });
}
_isStart = false;
if (_startThread != null)
{
try
{
// 检查线程状态,避免重复启动
if (_startThread.IsAlive)
{
// 给线程一个机会正常结束
if (!_startThread.Join(500)) // 等待500毫秒
{
try
{
_startThread.Abort(); // 强制终止
}
catch (ThreadStateException)
{
// 线程可能已经终止,忽略此异常
}
}
}
}
catch (Exception ex)
{
// 记录异常但不阻止重连
Console.WriteLine($"清理线程时异常: {ex.Message}");
}
finally
{
_startThread = null; // 确保设置为null
}
}
if (_reConnectCount < _maxConnectCount && IsReconnection)
{
StartConnect();
}
else
{
_timer.Stop();
StopConnect();
this.IsReconnection = false;
_reConnectCount = 0;
TcpClientStateInfo(string.Format("超过最大重连数,已断开服务器连接"), SocketState.Disconnect);
}
}
#endregion
#region
public void SendData(byte[] data)
{
try
{
if (data == null || data.Length == 0)
{
return;
}
if (Client != null && Client.WorkSocket != null && Client.WorkSocket.Connected)
{
//异步发送数据
//cModel.ClientSocket.Send(data);
Client.WorkSocket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), Client);
//timeoutreconnected = false;//连接超时的重连
//datareconnected = true;//接收不到心跳包的重连
}
}
catch (SocketException ex)
{
TcpClientErrorMsg(string.Format("向服务端发送数据时发生错误,错误原因:{0},行号{1}", ex.Message, ex.StackTrace));
}
}
public bool IsConnected
{
get
{
try
{
return Client != null &&
Client.WorkSocket != null &&
Client.WorkSocket.Connected;
}
catch
{
return false;
}
}
}
/// <summary>
/// 发送完数据之后的回调函数
/// </summary>
/// <param name="ar">Clicent</param>
private void SendCallback(IAsyncResult ar)
{
IClient iClient = (IClient)ar.AsyncState;
if (iClient == null)
return;
Socket handler = iClient.WorkSocket;
try
{
int bytesSent = handler.EndSend(ar);
}
catch (Exception ex)
{
TcpClientErrorMsg(string.Format("发送数据后回调时发生错误,错误原因:{0},行号{1}", ex.Message, ex.StackTrace));
}
}
#endregion
#region
/// <summary>
/// 当接收到数据之后的回调函数
/// </summary>
/// <param name="ar"></param>
private void ReadCallback(IAsyncResult ar)
{
if (Client == null || !_isStart)
return;
Socket handler = Client.WorkSocket;
try
{
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0 && bytesRead <= Client.BufferInfo.ReceivedBuffer.Length)
{
byte[] bytes = new byte[bytesRead];
Array.Copy(Client.BufferInfo.ReceivedBuffer, 0, bytes, 0, bytesRead);
TcpClientRecevice(bytes);
handler.BeginReceive(Client.BufferInfo.ReceivedBuffer, 0, Client.BufferInfo.ReceivedBuffer.Length,
0, new AsyncCallback(ReadCallback), Client);
}
else
{
if (IsReconnection)
{
Reconnect();
}
}
}
catch (Exception ex)
{
//if (datareconnected)
//{
// timeoutreconnected = false;//连接超时的重连
////IsStart = false;
StopConnect();
TcpClientErrorMsg(string.Format("接收数据失败,错误原因:{0},行号{1}", ex.Message, ex.StackTrace));
Reconnect();
//}
}
}
#endregion
#region
/// <summary>
/// 关闭相连的scoket以及关联的StateObject,释放所有的资源
/// </summary>
public void StopConnect()
{
IsStart = false;
if (Client != null)
{
var workSocket = Client.WorkSocket; // 提前保存引用
ShutdownClient(Client);
workSocket?.Close();
//if (Client.WorkSocket != null)
//{
// Client.WorkSocket.Close();
// //Client.WorkSocket?.Dispose();
//}
}
_conncetType = ConncetType.Conncet;
_reConnectCount = 0;//前面三个初始化
}
public void ShutdownClient(IClient iClient)
{
try
{
iClient.WorkSocket.Shutdown(SocketShutdown.Both);
}
catch
{
}
}
#endregion
#region
#region OnRecevice接收数据事件
[Description("接收数据事件")]
[Category("TcpClient事件")]
public event EventHandler<TcpClientReceviceEventArgs> OnRecevice;
protected virtual void TcpClientRecevice(byte[] data)
{
if (OnRecevice != null)
CommonMethod.EventInvoket(() => { OnRecevice(this, new TcpClientReceviceEventArgs(data)); });
}
#endregion
#region OnErrorMsg返回错误消息事件
[Description("返回错误消息事件")]
[Category("TcpClient事件")]
public event EventHandler<TcpClientErrorEventArgs> OnErrorMsg;
protected virtual void TcpClientErrorMsg(string msg)
{
if (OnErrorMsg != null)
CommonMethod.EventInvoket(() => { OnErrorMsg(this, new TcpClientErrorEventArgs(msg)); });
}
#endregion
#region OnStateInfo连接状态改变时返回连接状态事件
[Description("连接状态改变时返回连接状态事件")]
[Category("TcpClient事件")]
public event EventHandler<TcpClientStateEventArgs> OnStateInfo;
protected virtual void TcpClientStateInfo(string msg, SocketState state)
{
if (OnStateInfo != null)
CommonMethod.EventInvoket(() => { OnStateInfo(this, new TcpClientStateEventArgs(msg, state)); });
}
#endregion
#endregion
}
public enum ConncetType
{
Conncet,
ReConncet,
DisConncet
}
}

View File

@@ -0,0 +1,36 @@
namespace NetWorkHelper.TCP
{
partial class ITcpServer
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,151 @@
/********************************************************************
* *
* * Copyright (C) 2013-? Corporation All rights reserved.
* * 作者: BinGoo QQ315567586
* * 请尊重作者劳动成果,请保留以上作者信息,禁止用于商业活动。
* *
* * 创建时间2014-08-05
* * 说明:客户端类型管理
* *
********************************************************************/
using System.ComponentModel;
namespace NetWorkHelper.TClass
{
public enum ClientType
{
/// <summary>
/// 小车客户端
/// </summary>
[Description("小车客户端")]
CarType = 0,
/// <summary>
/// 轨道列车客户端
/// 包括(火车、地铁、高铁、动车)
/// </summary>
[Description("轨道列车客户端")]
TrainType = 1,
/// <summary>
/// 轨道监控PC客户端
/// </summary>
[Description("轨道监控PC客户端")]
TrainPcType = 2,
/// <summary>
/// Led客户端
/// </summary>
[Description("信号机客户端")]
LedType = 3,
/// <summary>
/// 监控调度客户端
/// </summary>
[Description("监控调度客户端")]
GpsClientType = 4,
/// <summary>
/// 信号机PC客户端
/// </summary>
[Description("信号机PC客户端")]
PcUtcClientType = 5,
/// <summary>
///公交服务客户端
/// </summary>
[Description("公交服务客户端")]
BusServerType = 6,
/// <summary>
/// 沙盘建筑背景灯控制客户端
/// </summary>
[Description("建筑灯客户端")]
PcLampClient = 7,
/// <summary>
/// 沙盘建筑背景灯客户端
/// </summary>
[Description("建筑灯PC客户端")]
LampClient = 8,
/// <summary>
/// 升降杆客户端
/// </summary>
[Description("升降杆客户端")]
MotorClient = 9,
/// <summary>
/// 无标记
/// </summary>
[Description("未知")]
None = 10,
/// <summary>
/// 华软客户端
/// </summary>
[Description("华软客户端")]
HuaRuan = 11,
/// <summary>
/// 电子警察客户端
/// </summary>
[Description("电子警察客户端")]
ElectronicPoliceClient = 12,
/// <summary>
/// 硬件地磁客户端
/// </summary>
[Description("硬件地磁客户端")]
Geomagnetic = 13,
/// <summary>
/// 网页地磁客户端
/// </summary>
[Description("网页地磁客户端")]
WebGeomagnetic = 14,
/// <summary>
/// andorid手机地磁客户端
/// </summary>
[Description(" Andorid手机地磁客户端")]
AndroidGeomagnetic = 15,
/// <summary>
///PC版地磁客户端
/// </summary>
[Description("地磁PC客户端")]
PcGeomagnetic = 16,
/// <summary>
///车辆监控客户端
/// </summary>
[Description("车辆监控客户端")]
CarMonitor = 17,
/// <summary>
///公交站闸机客户端
/// </summary>
[Description("公交站闸机客户端")]
RfidDoor = 18,
/// <summary>
///上海电气客户端
/// </summary>
[Description("上海电气客户端")]
ShangHaiDianQi = 19,
/// <summary>
/// 电子警察闪关灯客户端
/// </summary>
[Description("电子警察闪关灯客户端")]
ElectronicPoliceFlashLamp = 20,
/// <summary>
/// 停车场收费客户端
/// </summary>
[Description("停车场收费客户端")]
ParkingChargeClient = 21,
/// <summary>
/// 新版调度监控客户端
/// </summary>
[Description("新版调度监控客户端")]
DispatchClient = 22,
/// <summary>
/// 立体车库PC控制端
/// </summary>
[Description("立体车库PC控制端")]
PcStereoGarage = 23,
/// <summary>
/// 立体车库硬件
/// </summary>
[Description("立体车库硬件")]
StereoGarage = 24,
/// <summary>
/// 模拟驾驶客户端
/// </summary>
[Description("模拟驾驶客户端")]
VideoDrive = 25
}
}

View File

@@ -0,0 +1,39 @@
using System.Net;
namespace NetWorkHelper
{
internal class ControlTag
{
private string _md5;
private string _fileName;
private IPEndPoint _remoteIP;
public ControlTag(
string md5,
string fileName,
IPEndPoint remoteIP)
{
_md5 = md5;
_fileName = fileName;
_remoteIP = remoteIP;
}
public string MD5
{
get { return _md5; }
set { _md5 = value; }
}
public string FileName
{
get { return _fileName; }
set { _fileName = value; }
}
public IPEndPoint RemoteIP
{
get { return _remoteIP; }
set { _remoteIP = value; }
}
}
}

View File

@@ -0,0 +1,183 @@
/********************************************************************
* *
* * Copyright (C) 2013-? Corporation All rights reserved.
* * 作者: BinGoo QQ315567586
* * 请尊重作者劳动成果,请保留以上作者信息,禁止用于商业活动。
* *
* * 创建时间2014-08-05
* * 说明:
* *
********************************************************************/
using System.ComponentModel;
namespace NetWorkHelper
{
/// <summary>
/// Socket状态枚举
/// </summary>
public enum SocketState
{
/// <summary>
/// 正在连接服务端
/// </summary>
Connecting = 0,
/// <summary>
/// 已连接服务端
/// </summary>
Connected = 1,
/// <summary>
/// 重新连接服务端
/// </summary>
Reconnection = 2,
/// <summary>
/// 断开服务端连接
/// </summary>
Disconnect = 3,
/// <summary>
/// 正在监听
/// </summary>
StartListening = 4,
/// <summary>
/// 启动监听异常
/// </summary>
StartListeningError = 5,
/// <summary>
/// 停止监听
/// </summary>
StopListening = 6,
/// <summary>
/// 客户端上线
/// </summary>
ClientOnline = 7,
/// <summary>
/// 客户端下线
/// </summary>
ClientOnOff = 8
}
/// <summary>
/// 错误类型
/// </summary>
public enum SocketError
{
}
/// <summary>
/// 发送接收命令枚举
/// </summary>
public enum Command
{
/// <summary>
/// 发送请求接收文件
/// </summary>
RequestSendFile = 0x000001,
/// <summary>
/// 响应发送请求接收文件
/// </summary>
ResponeSendFile = 0x100001,
/// <summary>
/// 请求发送文件包
/// </summary>
RequestSendFilePack = 0x000002,
/// <summary>
/// 响应发送文件包
/// </summary>
ResponeSendFilePack = 0x100002,
/// <summary>
/// 请求取消发送文件包
/// </summary>
RequestCancelSendFile = 0x000003,
/// <summary>
/// 响应取消发送文件包
/// </summary>
ResponeCancelSendFile = 0x100003,
/// <summary>
/// 请求取消接收发送文件
/// </summary>
RequestCancelReceiveFile = 0x000004,
/// <summary>
/// 响应取消接收发送文件
/// </summary>
ResponeCancelReceiveFile = 0x100004,
/// <summary>
/// 请求发送文本消息
/// </summary>
RequestSendTextMSg = 0x000010,
}
/// <summary>
/// 消息类型
/// </summary>
public enum MsgType
{
/// <summary>
/// 文本消息
/// </summary>
TxtMsg = 0,
/// <summary>
/// 抖动窗体
/// </summary>
Shake = 1,
/// <summary>
/// 表情
/// </summary>
Face = 2,
/// <summary>
/// 图片
/// </summary>
Pic = 3
}
public enum ClientStyle
{
WebSocket,
PcSocket
}
public enum LogType
{
/// <summary>
/// 系统
/// </summary>
[Description("系统日志")]
System,
/// <summary>
/// 服务端
/// </summary>
[Description("服务端类型日志")]
Server,
/// <summary>
/// 客户端
/// </summary>
[Description("客户端类型日志")]
Client,
/// <summary>
/// 发送数据
/// </summary>
[Description("发送数据类型日志")]
SendData,
/// <summary>
/// 接收数据
/// </summary>
[Description("接收数据类型日志")]
ReceviedData,
/// <summary>
/// 发送数据返回结果
/// </summary>
[Description("发送数据返回结果类型日志")]
SendDataResult
}
}

View File

@@ -0,0 +1,47 @@
namespace NetWorkHelper
{
partial class AxUdpClient
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.fileTansfersContainer = new NetWorkHelper.FileTansfersContainer();
//
// fileTansfersContainer
//
this.fileTansfersContainer.AutoScroll = true;
this.fileTansfersContainer.Location = new System.Drawing.Point(0, 0);
this.fileTansfersContainer.Name = "fileTansfersContainer";
this.fileTansfersContainer.Size = new System.Drawing.Size(200, 100);
this.fileTansfersContainer.TabIndex = 0;
}
#endregion
private FileTansfersContainer fileTansfersContainer;
}
}

View File

@@ -0,0 +1,959 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Net;
using System.Text;
using System.Windows.Forms;
namespace NetWorkHelper
{
public partial class AxUdpClient : Component
{
#region
public AxUdpClient()
{
InitializeComponent();
}
public AxUdpClient(IContainer container)
{
container.Add(this);
InitializeComponent();
}
#endregion
#region
private UdpLibrary _udpLibrary;
/// <summary>
/// 文件发送列表管理器
/// </summary>
private Dictionary<string, SendFileManager> _sendFileManagerList;
/// <summary>
/// 文件接收列表管理器
/// </summary>
private Dictionary<string, ReceiveFileManager> _receiveFileManagerList;
private object _sendsyncLock = new object();
private object _receivesyncLock = new object();
#endregion
#region
/// <summary>
/// 传输协议是否启用AxUDPClient内部封装协议
/// </summary>
[Description("传输协议是否启用AxUDPClient内部封装协议")]
[Category("UDP客户端属性")]
public bool IsAxAgreement { get; set; } = true;
/// <summary>
/// UDP客户端基类
/// </summary>
[Description("UDP客户端基类")]
[Category("UDP客户端属性")]
public UdpLibrary UdpLibrary
{
get
{
if (_udpLibrary == null)
{
_udpLibrary = new UdpLibrary(LocalPort);
_udpLibrary.ReceiveData += new ReceiveDataEventHandler(UdpLibraryReceiveData);
}
return _udpLibrary;
}
}
/// <summary>
/// 文件发送列表管理器
/// </summary>
[Description("文件发送列表管理器")]
[Category("UDP客户端属性")]
public Dictionary<string, SendFileManager> SendFileManagerList
{
get
{
if (_sendFileManagerList == null)
{
_sendFileManagerList = new Dictionary<string, SendFileManager>(10);
}
return _sendFileManagerList;
}
}
/// <summary>
/// 文件接收列表管理器
/// </summary>
[Description("文件接收列表管理器")]
[Category("UDP客户端属性")]
public Dictionary<string, ReceiveFileManager> ReceiveFileManagerList
{
get
{
if (_receiveFileManagerList == null)
{
_receiveFileManagerList = new Dictionary<string, ReceiveFileManager>(10);
}
return _receiveFileManagerList;
}
}
/// <summary>
/// 远程监听IP
/// </summary>
[Description("远程监听IP")]
[Category("UDP客户端属性")]
public string RemoteIp { get; set; } = "127.0.0.1";
/// <summary>
/// 远程监听端口
/// </summary>
[Description("远程监听端口")]
[Category("UDP客户端属性")]
public int RemotePort { get; set; } = 8900;
/// <summary>
/// 本地监听IP
/// </summary>
[Description("本地监听IP")]
[Category("UDP客户端属性")]
public int LocalPort { get; set; } = 8899;
/// <summary>
/// 远程主机网络端点
/// </summary>
[Description("远程主机网络端点")]
[Category("UDP客户端属性")]
public IPEndPoint RemoteEp
{
get { return new IPEndPoint(IPAddress.Parse(RemoteIp), RemotePort); }
}
public FileTansfersContainer FileTansfersControl
{
get
{
if (fileTansfersContainer == null)
{
fileTansfersContainer = new FileTansfersContainer();
}
return fileTansfersContainer;
}
set
{
if (value == null)
fileTansfersContainer = new FileTansfersContainer();
else
{
fileTansfersContainer = value;
}
}
}
#endregion
#region
/// <summary>
/// 启动监听
/// </summary>
public void Start()
{
UdpLibrary.Start();
}
/// <summary>
/// 关闭监听
/// </summary>
public void Stop()
{
UdpLibrary.Stop();
}
/// <summary>
/// 继承Udp基类接收数据方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void UdpLibraryReceiveData(object sender, ReceiveDataEventArgs e)
{
//若不适用内部封装协议则只激活接受原始数据事件
if (!IsAxAgreement)
{
OnReceiveByte(e);
return;
}
MsgCell cell = new MsgCell();
cell.FromBuffer(e.Buffer);
switch (cell.MessageId)
{
case (int)Command.RequestSendTextMSg:
OnReceiveTextMsg((MsgTypeCell)cell.Data);
break;
case (int)Command.ResponeSendFile:
OnResponeSendFile((ResponeTraFransfersFile)cell.Data);
break;
case (int)Command.ResponeSendFilePack:
OnResponeSendFilePack((ResponeTraFransfersFile)cell.Data);
break;
case (int)Command.RequestCancelReceiveFile:
OnRequestCancelReceiveFile(cell.Data.ToString());
break;
case (int)Command.RequestSendFile:
OnStartRecieve((TraFransfersFileStart)cell.Data, e.RemoteIP);
break;
case (int)Command.RequestSendFilePack:
OnRecieveBuffer((TraFransfersFile)cell.Data, e.RemoteIP);
break;
case (int)Command.RequestCancelSendFile:
OnRequestCancelSendFile(cell.Data.ToString(), e.RemoteIP);
break;
}
}
/// <summary>
/// 返回是否允许发送,在发送列表中的文件不能重复发送(避免文件被占用导致错误)
/// </summary>
/// <param name="sendFileManager"></param>
/// <returns></returns>
public bool CanSend(SendFileManager sendFileManager)
{
return !SendFileManagerList.ContainsKey(sendFileManager.MD5);
}
/// <summary>
/// 发送文件
/// </summary>
/// <param name="fileName">文件路径(包含完整的文件名)</param>
public void SendFile(string fileName)
{
SendFileManager sendFileManager = new SendFileManager(fileName);
Image img = Icon.ExtractAssociatedIcon(fileName).ToBitmap();
SendFile(sendFileManager, img);
}
/// <summary>
/// 发送文件
/// </summary>
/// <param name="sendFileManager">需要发送的文件类</param>
/// <param name="image">文件ICO图标</param>
public void SendFile(SendFileManager sendFileManager, Image image)
{
if (SendFileManagerList.ContainsKey(sendFileManager.MD5))
{
throw new Exception(string.Format("文件 {0} 正在发送,不能发送重复的文件。", sendFileManager.FileName));
}
else
{
SendFileManagerList.Add(sendFileManager.MD5, sendFileManager);
sendFileManager.ReadFileBuffer += new ReadFileBufferEventHandler(SendFileManageReadFileBuffer);
TraFransfersFileStart ts = new TraFransfersFileStart(sendFileManager.MD5, sendFileManager.Name, image, sendFileManager.Length, sendFileManager.PartCount, sendFileManager.PartSize);
//添加
AddSendItems(sendFileManager, image);
Send((int)Command.RequestSendFile, ts);
}
}
/// <summary>
/// 取消发送
/// </summary>
/// <param name="md5">MD5校验文件</param>
public void CancelSend(string md5)
{
SendFileManager sendFileManager;
if (SendFileManagerList.TryGetValue(md5, out sendFileManager))
{
Send((int)Command.RequestCancelSendFile, md5);
lock (_sendsyncLock)
{
SendFileManagerList.Remove(md5);
sendFileManager.Dispose();
sendFileManager = null;
}
}
}
/// <summary>
/// 读取文件并发送文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SendFileManageReadFileBuffer(
object sender, ReadFileBufferEventArgs e)
{
SendFileManager sendFileManager = sender as SendFileManager;
TraFransfersFile ts = new TraFransfersFile(sendFileManager.MD5, e.Index, e.Buffer);
Send((int)Command.RequestSendFilePack, ts);
}
/// <summary>
/// 发送信息
/// </summary>
/// <param name="messageId">消息标识</param>
/// <param name="data">序列化数据</param>
public void Send(int messageId, object data)
{
Send(messageId, data, RemoteEp);
}
public void SendText(string strmsg)
{
byte[] dataBytes = Encoding.Default.GetBytes(strmsg);
MsgTypeCell msgTypeCell = new MsgTypeCell(MsgType.TxtMsg, dataBytes);
MsgCell cell = new MsgCell(0x000010, msgTypeCell);
UdpLibrary.Send(cell, RemoteEp);
}
public void SendImage(Image img)
{
MsgTypeCell msgTypeCell = new MsgTypeCell(MsgType.Pic, ImageHelper.ImageToBytes(img));
MsgCell cell = new MsgCell(0x000010, msgTypeCell);
UdpLibrary.Send(cell, RemoteEp);
}
/// <summary>
/// 发送信息
/// </summary>
/// <param name="messageId">消息标识</param>
/// <param name="data">序列化数据</param>
/// <param name="remoteIp">远程主机IP</param>
public void Send(int messageId, object data, IPEndPoint remoteIp)
{
MsgCell cell = new MsgCell(messageId, data);
UdpLibrary.Send(cell, remoteIp);
}
/// <summary>
/// 发送信息
/// </summary>
/// <param name="data">数据</param>
/// <param name="remoteIp">远程主机IP</param>
public void Send(byte[] data)
{
UdpLibrary.Send(data, RemoteEp);
}
/// <summary>
/// 响应发送文件方法
/// </summary>
/// <param name="data"></param>
private void OnResponeSendFile(ResponeTraFransfersFile data)
{
SendFileManager sendFileManager;
if (!SendFileManagerList.TryGetValue(data.MD5, out sendFileManager))
{
return;
}
if (data.Size > 0)
{
OnFileSendBuffer(new FileSendBufferEventArgs(sendFileManager, data.Size));
}
if (data.Index == 0)
{
if (sendFileManager != null)
{
OnFileSendAccept(new FileSendEventArgs(sendFileManager));
sendFileManager.Read(data.Index);
}
}
else
{
if (data.Index == -1)
{
OnFileSendRefuse(new FileSendEventArgs(sendFileManager));
}
SendFileManagerList.Remove(data.MD5);
sendFileManager.Dispose();
}
}
/// <summary>
/// 响应发送文件包方法
/// </summary>
/// <param name="data"></param>
private void OnResponeSendFilePack(ResponeTraFransfersFile data)
{
SendFileManager sendFileManager;
if (!SendFileManagerList.TryGetValue(data.MD5, out sendFileManager))
{
return;
}
if (data.Size > 0)
{
OnFileSendBuffer(new FileSendBufferEventArgs(sendFileManager, data.Size));
}
if (data.Index >= 0)
{
if (sendFileManager != null)
{
sendFileManager.Read(data.Index);
}
}
else
{
if (data.Index == -1)
{
OnFileSendRefuse(new FileSendEventArgs(sendFileManager));
}
else if (data.Index == -2)
{
OnFileSendComplete(new FileSendEventArgs(sendFileManager));
}
SendFileManagerList.Remove(data.MD5);
sendFileManager.Dispose();
}
}
/// <summary>
/// 请求取消接收文件方法
/// </summary>
/// <param name="md5"></param>
private void OnRequestCancelReceiveFile(string md5)
{
SendFileManager sendFileManager;
if (SendFileManagerList.TryGetValue(md5, out sendFileManager))
{
OnFileSendCancel(new FileSendEventArgs(sendFileManager));
lock (_sendsyncLock)
{
SendFileManagerList.Remove(md5);
sendFileManager.Dispose();
sendFileManager = null;
}
}
Send((int)Command.ResponeCancelReceiveFile, "OK");
}
#region
/// <summary>
/// 允许接收
/// </summary>
/// <param name="e"></param>
public void AcceptReceive(RequestSendFileEventArgs e)
{
TraFransfersFileStart traFransfersFileStart = e.TraFransfersFileStart;
IPEndPoint remoteIP = e.RemoteIP;
ResponeTraFransfersFile responeTraFransfersFile;
if (e.Cancel)
{
responeTraFransfersFile = new ResponeTraFransfersFile(traFransfersFileStart.MD5, 0, -1);
Send((int)Command.ResponeSendFile, responeTraFransfersFile, remoteIP);
}
else
{
ReceiveFileManager receiveFileManager;
if (!ReceiveFileManagerList.TryGetValue(traFransfersFileStart.MD5, out receiveFileManager))
{
receiveFileManager = new ReceiveFileManager(traFransfersFileStart.MD5, e.Path, traFransfersFileStart.FileName, traFransfersFileStart.PartCount, traFransfersFileStart.PartSize, traFransfersFileStart.Length, remoteIP);
receiveFileManager.ReceiveFileComplete += new FileReceiveCompleteEventHandler(ReceiveFileManagerReceiveFileComplete);
receiveFileManager.ReceiveFileTimeout += new EventHandler(ReceiveFileManagerReceiveFileTimeout);
ReceiveFileManagerList.Add(traFransfersFileStart.MD5, receiveFileManager);
receiveFileManager.Start();
}
responeTraFransfersFile = new ResponeTraFransfersFile(traFransfersFileStart.MD5, 0, 0);
Send((int)Command.ResponeSendFile, responeTraFransfersFile, remoteIP);
}
}
/// <summary>
/// 取消接收
/// </summary>
/// <param name="md5"></param>
/// <param name="remoteIP"></param>
public void CancelReceive(string md5, IPEndPoint remoteIP)
{
ReceiveFileManager receiveFileManager;
if (ReceiveFileManagerList.TryGetValue(md5, out receiveFileManager))
{
Send((int)Command.RequestCancelReceiveFile, md5, remoteIP);
lock (_receivesyncLock)
{
ReceiveFileManagerList.Remove(md5);
receiveFileManager.Dispose();
receiveFileManager = null;
}
}
}
/// <summary>
/// 完成接收文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ReceiveFileManagerReceiveFileComplete(
object sender, FileReceiveCompleteEventArgs e)
{
ReceiveFileManager receiveFileManager =
sender as ReceiveFileManager;
OnFileReceiveComplete(new FileReceiveEventArgs(receiveFileManager));
ReceiveFileManagerList.Remove(receiveFileManager.MD5);
}
private void ReceiveFileManagerReceiveFileTimeout(
object sender, EventArgs e)
{
ReceiveFileManager receiveFileManager =
sender as ReceiveFileManager;
ResponeTraFransfersFile responeTraFransfersFile =
new ResponeTraFransfersFile(
receiveFileManager.MD5,
0,
receiveFileManager.GetNextReceiveIndex());
Send(
(int)Command.ResponeSendFilePack,
responeTraFransfersFile,
receiveFileManager.RemoteIP);
}
#endregion
#endregion
#region
#region
#region ()
[Description("文件发送被取消事件\r\n(当发送文件正在被接收中时对方取消接收)")]
public event FileSendEventHandler FileSendCancel;
/// <summary>
/// 文件发送时被取消时触发事件
/// </summary>
/// <param name="e"></param>
protected virtual void OnFileSendCancel(FileSendEventArgs e)
{
FileTransfersItem item = e.SendFileManager.Tag as FileTransfersItem;
if (item != null)
{
Form.ActiveForm.BeginInvoke(new MethodInvoker(delegate ()
{
fileTansfersContainer.RemoveItem(item);
item.Dispose();
}));
}
FileSendCancel?.Invoke(this, e);
}
#endregion
#region
[Description("发送文件被允许接收时触发事件")]
public event FileSendEventHandler FileSendAccept;
/// <summary>
/// 文件被接收时触发事件
/// </summary>
/// <param name="e"></param>
protected virtual void OnFileSendAccept(FileSendEventArgs e)
{
FileTransfersItem item = e.SendFileManager.Tag as FileTransfersItem;
if (item != null)
{
Form.ActiveForm.BeginInvoke(new MethodInvoker(delegate ()
{
item.Start();
}));
}
FileSendAccept?.Invoke(this, e);
}
#endregion
#region
[Description("文件正在发送时触发事件")]
public event FileSendBufferEventHandler FileSendBuffer;
/// <summary>
/// 文件正在发送时触发事件
/// </summary>
/// <param name="e"></param>
protected virtual void OnFileSendBuffer(FileSendBufferEventArgs e)
{
FileTransfersItem item = e.SendFileManager.Tag as FileTransfersItem;
if (item != null)
{
Form.ActiveForm.BeginInvoke(new MethodInvoker(delegate ()
{
item.TotalTransfersSize += e.Size;
}));
}
FileSendBuffer?.Invoke(this, e);
}
#endregion
#region
[Description("发送文件被拒绝接收时触发事件")]
public event FileSendEventHandler FileSendRefuse;
/// <summary>
/// 发送文件被拒绝接收时触发事件
/// </summary>Refuse to receive file
/// <param name="e"></param>
protected virtual void OnFileSendRefuse(FileSendEventArgs e)
{
FileTransfersItem item = e.SendFileManager.Tag as FileTransfersItem;
if (item != null)
{
Form.ActiveForm.BeginInvoke(new MethodInvoker(delegate ()
{
fileTansfersContainer.RemoveItem(item);
item.Dispose();
}));
}
FileSendRefuse?.Invoke(this, e);
}
#endregion
#region
[Description("文件发送完成时触发事件")]
public event FileSendEventHandler FileSendComplete;
/// <summary>
/// 文件发送完成时触发事件
/// </summary>
/// <param name="e"></param>
protected virtual void OnFileSendComplete(FileSendEventArgs e)
{
FileTransfersItem item = e.SendFileManager.Tag as FileTransfersItem;
if (item != null)
{
Form.ActiveForm.BeginInvoke(new MethodInvoker(delegate ()
{
fileTansfersContainer.RemoveItem(item);
item.Dispose();
}));
}
FileSendComplete?.Invoke(this, e);
}
#endregion
#region
/// <summary>
/// 取消发送文件事件方法
/// </summary>
/// <param name="md5"></param>
/// <param name="remoteIP"></param>
private void OnRequestCancelSendFile(string md5, IPEndPoint remoteIP)
{
ReceiveFileManager receiveFileManager;
if (ReceiveFileManagerList.TryGetValue(md5, out receiveFileManager))
{
OnFileReceiveCancel(new FileReceiveEventArgs(receiveFileManager));
lock (_receivesyncLock)
{
ReceiveFileManagerList.Remove(md5);
receiveFileManager.Dispose();
receiveFileManager = null;
}
}
else
{
FileReceiveEventArgs fe = new FileReceiveEventArgs();
fe.Tag = md5;
OnFileReceiveCancel(fe);
}
Send(
(int)Command.ResponeCancelSendFile, "OK", remoteIP);
}
#endregion
#endregion
#region
#region
public delegate void ReceiveTextMsgEventHandler(MsgTypeCell msgTypeCell);
[Description("接收文本数据事件")]
public event ReceiveTextMsgEventHandler ReceiveTextMsg;
/// <summary>
/// 文件被接收时触发事件
/// </summary>
/// <param name="bytes"></param>
protected virtual void OnReceiveTextMsg(MsgTypeCell msgTypeCell)
{
ReceiveTextMsg?.Invoke(msgTypeCell);
}
#endregion
#region
[Description("请求接收文件响应时触发事件")]
public event RequestSendFileEventHandler FileRecieveRequest;
/// <summary>
/// 请求接收文件响应时触发事件
/// </summary>
/// <param name="e"></param>
protected virtual void OnFileRecieveRequest(RequestSendFileEventArgs e)
{
AddReadyReceiveItem(e);
FileRecieveRequest?.Invoke(this, e);
}
#endregion
#region
[Description("文件被读取时(正在读取)触发事件")]
public event FileReceiveBufferEventHandler FileReceiveBuffer;
/// <summary>
/// 文件被读取时(正在读取)触发事件
/// </summary>
/// <param name="e"></param>
protected virtual void OnFileReceiveBuffer(FileReceiveBufferEventArgs e)
{
FileTransfersItem item = fileTansfersContainer.Search(e.ReceiveFileManager.MD5);
if (item != null)
{
Form.ActiveForm.BeginInvoke(new MethodInvoker(delegate ()
{
item.TotalTransfersSize += e.Size;
}));
}
FileReceiveBuffer?.Invoke(this, e);
}
#endregion
#region
[Description("文件接收完成时触发事件")]
public event FileReceiveEventHandler FileReceiveComplete;
/// <summary>
/// 文件接收完成时触发事件
/// </summary>
/// <param name="e"></param>
protected virtual void OnFileReceiveComplete(FileReceiveEventArgs e)
{
Form.ActiveForm.BeginInvoke(new MethodInvoker(delegate ()
{
fileTansfersContainer.RemoveItem(e.ReceiveFileManager.MD5);
}));
FileReceiveComplete?.Invoke(this, e);
}
#endregion
#region
[Description("接收文件被取消时触发事件\r\n(当正在接收对方文件时对方取消发送)")]
public event FileReceiveEventHandler FileReceiveCancel;
/// <summary>
/// 文件接收时被取消发送触发事件
/// </summary>
/// <param name="e"></param>
protected virtual void OnFileReceiveCancel(FileReceiveEventArgs e)
{
string md5 = string.Empty;
if (e.ReceiveFileManager != null)
{
md5 = e.ReceiveFileManager.MD5;
}
else
{
md5 = e.Tag.ToString();
}
FileTransfersItem item = fileTansfersContainer.Search(md5);
Form.ActiveForm.BeginInvoke(new MethodInvoker(delegate ()
{
fileTansfersContainer.RemoveItem(item);
}));
FileReceiveCancel?.Invoke(this, e);
}
#endregion
#region
/// <summary>
/// 接收文件事件方法
/// </summary>
/// <param name="traFransfersFile"></param>
/// <param name="remoteEp"></param>
private void OnRecieveBuffer(TraFransfersFile traFransfersFile, IPEndPoint remoteEp)
{
ReceiveFileManager receiveFileManager;
if (!ReceiveFileManagerList.TryGetValue(traFransfersFile.MD5, out receiveFileManager))
{
return;
}
if (receiveFileManager != null)
{
ResponeTraFransfersFile responeTraFransfersFile;
int size = receiveFileManager.ReceiveBuffer(traFransfersFile.Index, traFransfersFile.Buffer);
if (receiveFileManager.Completed)
{
responeTraFransfersFile = new ResponeTraFransfersFile(traFransfersFile.MD5, size, -2);
Send((int)Command.ResponeSendFilePack, responeTraFransfersFile, remoteEp);
}
else
{
responeTraFransfersFile = new ResponeTraFransfersFile(traFransfersFile.MD5, size, receiveFileManager.GetNextReceiveIndex());
Send((int)Command.ResponeSendFilePack, responeTraFransfersFile, remoteEp);
}
OnFileReceiveBuffer(new FileReceiveBufferEventArgs(receiveFileManager, traFransfersFile.Buffer.Length));
}
}
#endregion
#region
/// <summary>
/// 开始接收文件事件方法(尚未开始接收文件)
/// </summary>
/// <param name="traFransfersFileStart"></param>
/// <param name="remoteEp"></param>
private void OnStartRecieve(TraFransfersFileStart traFransfersFileStart, IPEndPoint remoteEp)
{
OnFileRecieveRequest(new RequestSendFileEventArgs(traFransfersFileStart, remoteEp));
}
#endregion
#endregion
#region
public delegate void ReceiveByteEventHandler(ReceiveDataEventArgs e);
[Description("接收文本数据事件")]
public event ReceiveByteEventHandler ReceiveByte;
/// <summary>
/// 文件被接收时触发事件
/// </summary>
/// <param name="e"></param>
protected virtual void OnReceiveByte(ReceiveDataEventArgs e)
{
ReceiveByte?.Invoke(e);
}
#endregion
#endregion
#region FileTransfersItem子项
#region Items变量
private Color _baseColor = Color.FromArgb(255, 192, 128);
private Color _borderColor = Color.FromArgb(224, 224, 224);
private Color _progressBarBarColor = Color.SteelBlue;
private Color _progressBarBorderColor = Color.LightGray;
private Color _progressBarTextColor = Color.White;
#endregion
#region
/// <summary>
/// 添加准备接收文件Item
/// </summary>
/// <param name="e"></param>
public void AddReadyReceiveItem(RequestSendFileEventArgs e)
{
TraFransfersFileStart traFransfersFileStart = e.TraFransfersFileStart;
Form.ActiveForm.BeginInvoke(new MethodInvoker(delegate ()
{
FileTransfersItem item = fileTansfersContainer.AddItem(traFransfersFileStart.MD5, "接收文件", traFransfersFileStart.FileName, traFransfersFileStart.Image, traFransfersFileStart.Length, FileTransfersItemStyle.ReadyReceive);
item.BaseColor = _baseColor;
item.BorderColor = _borderColor;
item.ProgressBarBarColor = _progressBarBarColor;
item.ProgressBarBorderColor = _progressBarBorderColor;
item.ProgressBarTextColor = _progressBarTextColor;
item.Tag = e;
item.SaveButtonClick += new EventHandler(ItemSaveButtonClick);
item.SaveToButtonClick += new EventHandler(ItemSaveToButtonClick);
item.RefuseButtonClick += new EventHandler(ItemRefuseButtonClick);
fileTansfersContainer.ResumeLayout(true);
}));
}
#region
/// <summary>
/// 文件另存为按钮事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ItemSaveToButtonClick(object sender, EventArgs e)
{
FileTransfersItem item = sender as FileTransfersItem;
RequestSendFileEventArgs rse = item.Tag as RequestSendFileEventArgs;
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
rse.Path = fbd.SelectedPath;
ControlTag tag = new ControlTag(rse.TraFransfersFileStart.MD5, rse.TraFransfersFileStart.FileName, rse.RemoteIP);
item.Tag = tag;
item.Style = FileTransfersItemStyle.Receive;
item.CancelButtonClick += new EventHandler(ItemCancelButtonClick);
item.Start();
this.AcceptReceive(rse);
}
}
/// <summary>
/// 保存文件按钮事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ItemSaveButtonClick(object sender, EventArgs e)
{
FileTransfersItem item = sender as FileTransfersItem;
RequestSendFileEventArgs rse = item.Tag as RequestSendFileEventArgs;
//自动保存在程序根目录下
rse.Path = Application.StartupPath;
ControlTag tag = new ControlTag(rse.TraFransfersFileStart.MD5, rse.TraFransfersFileStart.FileName, rse.RemoteIP);
item.Tag = tag;
item.Style = FileTransfersItemStyle.Receive;
item.CancelButtonClick += new EventHandler(ItemCancelButtonClick);
item.Start();
this.AcceptReceive(rse);
}
/// <summary>
/// 拒绝接收文件按钮事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ItemRefuseButtonClick(object sender, EventArgs e)
{
FileTransfersItem item = sender as FileTransfersItem;
RequestSendFileEventArgs rse = item.Tag as RequestSendFileEventArgs;
rse.Cancel = true;
fileTansfersContainer.RemoveItem(item);
item.Dispose();
AcceptReceive(rse);
}
/// <summary>
/// 取消按钮事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ItemCancelButtonClick(object sender, EventArgs e)
{
FileTransfersItem item = sender as FileTransfersItem;
ControlTag tag = item.Tag as ControlTag;
CancelReceive(tag.MD5, tag.RemoteIP);
fileTansfersContainer.RemoveItem(item);
item.Dispose();
}
#endregion
#endregion
#region
/// <summary>
/// 添加发送文件控件Item
/// </summary>
/// <param name="sendFileManager"></param>
/// <param name="image"></param>
public void AddSendItems(SendFileManager sendFileManager, Image image)
{
FileTransfersItem item = fileTansfersContainer.AddItem(sendFileManager.MD5, "发送文件", sendFileManager.Name, image, sendFileManager.Length, FileTransfersItemStyle.Send);
item.BaseColor = Color.FromArgb(224, 224, 224);
item.BorderColor = _borderColor;
item.ProgressBarBarColor = _progressBarBarColor;
item.ProgressBarBorderColor = _progressBarBorderColor;
item.ProgressBarTextColor = _progressBarTextColor;
item.CancelButtonClick += new EventHandler(ItemSendCancelButtonClick);
item.Tag = sendFileManager;
sendFileManager.Tag = item;
}
#region
private void ItemSendCancelButtonClick(object sender, EventArgs e)
{
FileTransfersItem item = sender as FileTransfersItem;
SendFileManager sendFileManager = item.Tag as SendFileManager;
this.CancelSend(sendFileManager.MD5);
fileTansfersContainer.RemoveItem(item);
}
#endregion
#endregion
#endregion
}
}

View File

@@ -0,0 +1,126 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="fileTansfersContainer.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="$this.TrayLargeIcon" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</metadata>
</root>

View File

@@ -0,0 +1,10 @@
namespace NetWorkHelper
{
internal enum ControlState
{
Normal,
Hover,
Pressed,
Focused
}
}

View File

@@ -0,0 +1,162 @@
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace NetWorkHelper
{
/// <summary>
/// <20><><EFBFBD>ͽ<EFBFBD><CDBD><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// </summary>
public class FileTansfersContainer : Panel
{
private IFileTransfersItemText _fileTransfersItemText;
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public IFileTransfersItemText FileTransfersItemText
{
get
{
if (this._fileTransfersItemText == null)
{
this._fileTransfersItemText = new FileTransfersItemText();
}
return this._fileTransfersItemText;
}
set
{
this._fileTransfersItemText = value;
foreach (FileTransfersItem item in base.Controls)
{
item.FileTransfersText = this._fileTransfersItemText;
}
}
}
public FileTansfersContainer()
{
this.AutoScroll = true;
}
private bool _isAutomaticShowHide = true;
[Description("<22>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Զ<EFBFBD><D4B6><EFBFBD>ʾ<EFBFBD><CABE><EFBFBD>ؿؼ<D8BF>\r\n(trueΪ<65><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>н<EFBFBD><D0BD><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD>ʱ<EFBFBD>Զ<EFBFBD><D4B6><EFBFBD>ʾ<EFBFBD><CABE><EFBFBD>ؿؼ<D8BF>)")]
public bool IsAutomaticShowHide
{
get { return _isAutomaticShowHide; }
set { _isAutomaticShowHide = value; }
}
public FileTransfersItem AddItem(string text, string fileName, Image image, long fileSize, FileTransfersItemStyle style)
{
FileTransfersItem item = new FileTransfersItem();
item.Text = text;
item.FileName = fileName;
item.Image = image;
item.FileSize = fileSize;
item.Style = style;
item.FileTransfersText = this.FileTransfersItemText;
item.Dock = DockStyle.Top;
base.SuspendLayout();
base.Controls.Add(item);
item.BringToFront();
base.ResumeLayout(true);
if (IsAutomaticShowHide)
{
base.Visible = base.Controls.Count > 0 ? true : false;
}
return item;
}
/// <summary>
/// <20><><EFBFBD><EFBFBD>FileTransfersItem<65>ļ<EFBFBD><C4BC><EFBFBD>
/// </summary>
/// <param name="md5"><3E><><EFBFBD>ƣ<EFBFBD>MD5У<35><D0A3>ֵ<EFBFBD><D6B5></param>
/// <param name="typetext"><3E>ļ<EFBFBD><C4BC><EFBFBD><EFBFBD>ͣ<EFBFBD><CDA3><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD>/<2F><><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC><EFBFBD></param>
/// <param name="fileName"><3E>ļ<EFBFBD>·<EFBFBD><C2B7></param>
/// <param name="image"><3E>ļ<EFBFBD>ͼ<EFBFBD><CDBC></param>
/// <param name="fileSize"><3E>ļ<EFBFBD><C4BC><EFBFBD>С</param>
/// <param name="style"><3E>ļ<EFBFBD>״̬<D7B4><CCAC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><E9BFB4>FileTransfersItemStyle<6C><65></param>
/// <returns></returns>
public FileTransfersItem AddItem(string md5, string typetext, string fileName, Image image, long fileSize, FileTransfersItemStyle style)
{
FileTransfersItem item = new FileTransfersItem();
item.Name = md5;
item.Text = typetext;
item.FileName = fileName;
item.Image = image;
item.FileSize = fileSize;
item.Style = style;
item.FileTransfersText = this.FileTransfersItemText;
item.Dock = DockStyle.Top;
base.SuspendLayout();
base.Controls.Add(item);
item.BringToFront();
base.ResumeLayout(true);
if (IsAutomaticShowHide)
{
base.Visible = base.Controls.Count > 0 ? true : false;
}
return item;
}
/// <summary>
/// <20>Ƴ<EFBFBD><C6B3><EFBFBD>ӦFileTransfersItem
/// </summary>
/// <param name="item">FileTransfersItem</param>
public void RemoveItem(FileTransfersItem item)
{
base.Controls.Remove(item);
if (IsAutomaticShowHide)
{
base.Visible = base.Controls.Count > 0 ? true : false;
}
}
/// <summary>
/// <20><><EFBFBD><EFBFBD>MD5<44><35>ֵ<EFBFBD>Ƴ<EFBFBD><C6B3><EFBFBD>Ӧ<EFBFBD>ؼ<EFBFBD>
/// </summary>
/// <param name="md5"></param>
public void RemoveItem(string md5)
{
base.Controls.RemoveByKey(md5);
if (IsAutomaticShowHide)
{
base.Visible = base.Controls.Count > 0 ? true : false;
}
}
public void RemoveItem(Predicate<FileTransfersItem> match)
{
FileTransfersItem itemRemove = null;
foreach (FileTransfersItem item in base.Controls)
{
if (match(item))
{
itemRemove = item;
}
}
base.Controls.Remove(itemRemove);
if (IsAutomaticShowHide)
{
base.Visible = base.Controls.Count > 0 ? true : false;
}
}
/// <summary>
/// <20><><EFBFBD><EFBFBD>MD5У<35><D0A3>ֵ<EFBFBD><D6B5><EFBFBD><EFBFBD>FileTransfersItem
/// </summary>
/// <param name="md5"></param>
/// <returns></returns>
public FileTransfersItem Search(string md5)
{
return base.Controls[md5] as FileTransfersItem;
}
public FileTransfersItem Search(Predicate<FileTransfersItem> match)
{
FileTransfersItem result;
foreach (FileTransfersItem item in base.Controls)
{
if (match(item))
{
result = item;
return result;
}
}
result = null;
return result;
}
}
}

View File

@@ -0,0 +1,986 @@
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Windows.Forms;
namespace NetWorkHelper
{
public class FileTransfersItem : Control
{
private Image _image;
private string _fileName;
private long _fileSize;
private long _totalTransfersSize;
private FileTransfersItemStyle _style;
private RoundStyle _roundStyle = RoundStyle.All;
private int _radius = 8;
private Color _baseColor = Color.FromArgb(191, 233, 255);
private Color _borderColor = Color.FromArgb(118, 208, 225);
private Color _progressBarTrackColor = Color.Gainsboro;
private Color _progressBarBarColor = Color.FromArgb(191, 233, 255);
private Color _progressBarBorderColor = Color.FromArgb(118, 208, 225);
private Color _progressBarTextColor = Color.FromArgb(0, 95, 147);
private int _interval = 1000;
private IFileTransfersItemText _fileTransfersText;
private DateTime _startTime = DateTime.Now;
private System.Threading.Timer _timer;
private ControlState _saveState;
private ControlState _saveToState;
private ControlState _refuseState;
private ControlState _cancelState;
private static readonly object EventSaveButtonClick = new object();
private static readonly object EventSaveToButtonClick = new object();
private static readonly object EventRefuseButtonClick = new object();
private static readonly object EventCancelButtonClick = new object();
public event EventHandler SaveButtonClick
{
add
{
base.Events.AddHandler(FileTransfersItem.EventSaveButtonClick, value);
}
remove
{
base.Events.RemoveHandler(FileTransfersItem.EventSaveButtonClick, value);
}
}
public event EventHandler SaveToButtonClick
{
add
{
base.Events.AddHandler(FileTransfersItem.EventSaveToButtonClick, value);
}
remove
{
base.Events.RemoveHandler(FileTransfersItem.EventSaveToButtonClick, value);
}
}
public event EventHandler RefuseButtonClick
{
add
{
base.Events.AddHandler(FileTransfersItem.EventRefuseButtonClick, value);
}
remove
{
base.Events.RemoveHandler(FileTransfersItem.EventRefuseButtonClick, value);
}
}
public event EventHandler CancelButtonClick
{
add
{
base.Events.AddHandler(FileTransfersItem.EventCancelButtonClick, value);
}
remove
{
base.Events.RemoveHandler(FileTransfersItem.EventCancelButtonClick, value);
}
}
[DefaultValue(typeof(Icon), "null")]
public Image Image
{
get
{
return this._image;
}
set
{
this._image = value;
base.Invalidate();
}
}
[DefaultValue("")]
public string FileName
{
get
{
return this._fileName;
}
set
{
this._fileName = value;
base.Invalidate();
}
}
[DefaultValue(0)]
public long FileSize
{
get
{
return this._fileSize;
}
set
{
this._fileSize = value;
base.Invalidate();
}
}
[DefaultValue(0)]
public long TotalTransfersSize
{
get
{
return this._totalTransfersSize;
}
set
{
if (this._totalTransfersSize != value)
{
if (value > this._fileSize)
{
this._totalTransfersSize = this._fileSize;
}
else
{
this._totalTransfersSize = value;
}
base.Invalidate(this.ProgressBarRect);
base.Invalidate(this.TransfersSizeRect);
}
}
}
[DefaultValue(typeof(FileTransfersItemStyle), "0")]
public FileTransfersItemStyle Style
{
get
{
return this._style;
}
set
{
this._style = value;
base.Invalidate();
}
}
[DefaultValue(typeof(RoundStyle), "1")]
public RoundStyle RoundStyle
{
get
{
return this._roundStyle;
}
set
{
if (this._roundStyle != value)
{
this._roundStyle = value;
base.Invalidate();
}
}
}
[DefaultValue(8)]
public int Radius
{
get
{
return this._radius;
}
set
{
if (this._radius != value)
{
this._radius = ((value < 1) ? 1 : value);
base.Invalidate();
}
}
}
[DefaultValue(typeof(Color), "191, 233, 255")]
public Color BaseColor
{
get
{
return this._baseColor;
}
set
{
this._baseColor = value;
base.Invalidate();
}
}
[DefaultValue(typeof(Color), "118, 208, 225")]
public Color BorderColor
{
get
{
return this._borderColor;
}
set
{
this._borderColor = value;
base.Invalidate();
}
}
[DefaultValue(typeof(Color), "Gainsboro")]
public Color ProgressBarTrackColor
{
get
{
return this._progressBarTrackColor;
}
set
{
this._progressBarTrackColor = value;
base.Invalidate(this.ProgressBarRect);
}
}
[DefaultValue(typeof(Color), "191, 233, 255")]
public Color ProgressBarBarColor
{
get
{
return this._progressBarBarColor;
}
set
{
this._progressBarBarColor = value;
base.Invalidate(this.ProgressBarRect);
}
}
[DefaultValue(typeof(Color), "118, 208, 225")]
public Color ProgressBarBorderColor
{
get
{
return this._progressBarBorderColor;
}
set
{
this._progressBarBorderColor = value;
base.Invalidate(this.ProgressBarRect);
}
}
[DefaultValue(typeof(Color), "0, 95, 147")]
public Color ProgressBarTextColor
{
get
{
return this._progressBarTextColor;
}
set
{
this._progressBarTextColor = value;
base.Invalidate(this.ProgressBarRect);
}
}
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public IFileTransfersItemText FileTransfersText
{
get
{
if (this._fileTransfersText == null)
{
this._fileTransfersText = new FileTransfersItemText();
}
return this._fileTransfersText;
}
set
{
this._fileTransfersText = value;
base.Invalidate();
}
}
[DefaultValue(1000)]
public int Interval
{
get
{
return this._interval;
}
set
{
this._interval = value;
}
}
internal System.Threading.Timer Timer
{
get
{
if (this._timer == null)
{
this._timer = new System.Threading.Timer(delegate (object obj)
{
if (!base.Disposing)
{
if (!base.Disposing)
{
base.BeginInvoke((MethodInvoker)delegate ()
{
base.Invalidate(this.SpeedRect);
});
}
}
}, null, -1, this._interval);
//System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(timer_Elapsed), null, -1, this._interval);
}
return this._timer;
}
}
internal Rectangle ImageRect
{
get
{
return new Rectangle(6, 6, 32, 32);
}
}
internal Rectangle TextRect
{
get
{
return new Rectangle(43, 6, base.Width - 49, 16);
}
}
internal Rectangle FileNameRect
{
get
{
return new Rectangle(43, 22, base.Width - 49, 16);
}
}
internal Rectangle ProgressBarRect
{
get
{
return new Rectangle(4, 41, base.Width - 8, 16);
}
}
internal Rectangle SpeedRect
{
get
{
return new Rectangle(6, 60, base.Width / 2 - 8, 16);
}
}
internal Rectangle TransfersSizeRect
{
get
{
return new Rectangle(base.Width / 2, 60, base.Width / 2 - 6, 16);
}
}
internal Rectangle RefuseReceiveRect
{
get
{
Size size = TextRenderer.MeasureText(this.FileTransfersText.RefuseReceive, this.Font);
return new Rectangle(base.Width - size.Width - 7, 79, size.Width, size.Height);
}
}
internal Rectangle CancelTransfersRect
{
get
{
Size size = TextRenderer.MeasureText(this.FileTransfersText.CancelTransfers, this.Font);
return new Rectangle(base.Width - size.Width - 7, 79, size.Width, size.Height);
}
}
internal Rectangle SaveToRect
{
get
{
Size size = TextRenderer.MeasureText(this.FileTransfersText.SaveTo, this.Font);
return new Rectangle(this.RefuseReceiveRect.X - size.Width - 20, 79, size.Width, size.Height);
}
}
internal Rectangle SaveRect
{
get
{
Size size = TextRenderer.MeasureText(this.FileTransfersText.Save, this.Font);
return new Rectangle(this.SaveToRect.X - size.Width - 20, 79, size.Width, size.Height);
}
}
protected override Size DefaultSize
{
get
{
return new Size(200, 97);
}
}
private ControlState SaveState
{
get
{
return this._saveState;
}
set
{
if (this._saveState != value)
{
this._saveState = value;
base.Invalidate(this.Inflate(this.SaveRect));
}
}
}
private ControlState SaveToState
{
get
{
return this._saveToState;
}
set
{
if (this._saveToState != value)
{
this._saveToState = value;
base.Invalidate(this.Inflate(this.SaveToRect));
}
}
}
private ControlState RefuseState
{
get
{
return this._refuseState;
}
set
{
if (this._refuseState != value)
{
this._refuseState = value;
base.Invalidate(this.Inflate(this.RefuseReceiveRect));
}
}
}
private ControlState CancelState
{
get
{
return this._cancelState;
}
set
{
if (this._cancelState != value)
{
this._cancelState = value;
base.Invalidate(this.Inflate(this.CancelTransfersRect));
}
}
}
public FileTransfersItem()
{
this.SetStyles();
}
public void Start()
{
this._startTime = DateTime.Now;
this.Timer.Change(this._interval, this._interval);
}
protected virtual void OnSaveButtonClick(EventArgs e)
{
EventHandler handler = base.Events[FileTransfersItem.EventSaveButtonClick] as EventHandler;
if (handler != null)
{
handler(this, e);
}
}
protected virtual void OnSaveToButtonClick(EventArgs e)
{
EventHandler handler = base.Events[FileTransfersItem.EventSaveToButtonClick] as EventHandler;
if (handler != null)
{
handler(this, e);
}
}
protected virtual void OnRefuseButtonClick(EventArgs e)
{
EventHandler handler = base.Events[FileTransfersItem.EventRefuseButtonClick] as EventHandler;
if (handler != null)
{
handler(this, e);
}
}
protected virtual void OnCancelButtonClick(EventArgs e)
{
EventHandler handler = base.Events[FileTransfersItem.EventCancelButtonClick] as EventHandler;
if (handler != null)
{
handler(this, e);
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
Point point = e.Location;
switch (this._style)
{
case FileTransfersItemStyle.Send:
case FileTransfersItemStyle.Receive:
if (this.CancelTransfersRect.Contains(point))
{
this.CancelState = ControlState.Hover;
}
else
{
this.CancelState = ControlState.Normal;
}
break;
case FileTransfersItemStyle.ReadyReceive:
if (this.SaveRect.Contains(point))
{
this.SaveState = ControlState.Hover;
}
else
{
this.SaveState = ControlState.Normal;
}
if (this.SaveToRect.Contains(point))
{
this.SaveToState = ControlState.Hover;
}
else
{
this.SaveToState = ControlState.Normal;
}
if (this.RefuseReceiveRect.Contains(point))
{
this.RefuseState = ControlState.Hover;
}
else
{
this.RefuseState = ControlState.Normal;
}
break;
}
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button == MouseButtons.Left)
{
Point point = e.Location;
switch (this._style)
{
case FileTransfersItemStyle.Send:
case FileTransfersItemStyle.Receive:
if (this.CancelTransfersRect.Contains(point))
{
this.CancelState = ControlState.Pressed;
}
break;
case FileTransfersItemStyle.ReadyReceive:
if (this.SaveRect.Contains(point))
{
this.SaveState = ControlState.Pressed;
}
if (this.SaveToRect.Contains(point))
{
this.SaveToState = ControlState.Pressed;
}
if (this.RefuseReceiveRect.Contains(point))
{
this.RefuseState = ControlState.Pressed;
}
break;
}
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (e.Button == MouseButtons.Left)
{
Point point = e.Location;
switch (this._style)
{
case FileTransfersItemStyle.Send:
case FileTransfersItemStyle.Receive:
if (this.CancelTransfersRect.Contains(point))
{
this.CancelState = ControlState.Hover;
this.OnCancelButtonClick(e);
}
else
{
this.CancelState = ControlState.Normal;
}
break;
case FileTransfersItemStyle.ReadyReceive:
if (this.SaveRect.Contains(point))
{
this.SaveState = ControlState.Hover;
this.OnSaveButtonClick(e);
}
else
{
this.SaveState = ControlState.Normal;
}
if (this.SaveToRect.Contains(point))
{
this.SaveToState = ControlState.Hover;
this.OnSaveToButtonClick(e);
}
else
{
this.SaveToState = ControlState.Normal;
}
if (this.RefuseReceiveRect.Contains(point))
{
this.RefuseState = ControlState.Hover;
this.OnRefuseButtonClick(e);
}
else
{
this.RefuseState = ControlState.Normal;
}
break;
}
}
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
switch (this._style)
{
case FileTransfersItemStyle.Send:
case FileTransfersItemStyle.Receive:
this.CancelState = ControlState.Normal;
break;
case FileTransfersItemStyle.ReadyReceive:
this.SaveState = ControlState.Normal;
this.SaveToState = ControlState.Normal;
this.RefuseState = ControlState.Normal;
break;
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics g = e.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBilinear;
g.TextRenderingHint = TextRenderingHint.AntiAlias;
if (this.Image != null)
{
g.DrawImage(this.Image, this.ImageRect, new Rectangle(Point.Empty, this.Image.Size), GraphicsUnit.Pixel);
}
TextFormatFlags flags = TextFormatFlags.EndEllipsis | TextFormatFlags.SingleLine;
TextRenderer.DrawText(g, this.Text, this.Font, this.TextRect, this.ForeColor, flags);
TextRenderer.DrawText(g, this.FileName, this.Font, this.FileNameRect, this.ForeColor, flags);
Rectangle rect = this.ProgressBarRect;
Color innerBorderColor = Color.FromArgb(200, 255, 255, 255);
this.RenderBackgroundInternal(g, rect, this._progressBarTrackColor, this._progressBarBorderColor, innerBorderColor, RoundStyle.None, 0, 0.0f, false, false, LinearGradientMode.Vertical);
if (this.FileSize != 0L)
{
float percent = (float)this.TotalTransfersSize / (float)this.FileSize;
int width = (int)((float)rect.Width * percent);
width = Math.Min(width, rect.Width - 2);
if (width > 5)
{
Rectangle barRect = new Rectangle(rect.X + 1, rect.Y + 1, width, rect.Height - 2);
this.RenderBackgroundInternal(g, barRect, this._progressBarBarColor, this._progressBarBarColor, innerBorderColor, RoundStyle.None, 0, 0.0f, false, false, LinearGradientMode.Vertical);
}
TextRenderer.DrawText(g, percent.ToString("0.0%"), this.Font, rect, this._progressBarTextColor, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
string transferSizeText = string.Format("{0}/{1}", this.GetText((double)this._totalTransfersSize), this.GetText((double)this._fileSize));
TextRenderer.DrawText(g, transferSizeText, this.Font, this.TransfersSizeRect, this.ForeColor, TextFormatFlags.Right | TextFormatFlags.VerticalCenter);
if (this._totalTransfersSize != 0L && !base.DesignMode)
{
TextRenderer.DrawText(g, this.GetSpeedText(), this.Font, this.SpeedRect, this.ForeColor, TextFormatFlags.VerticalCenter);
}
}
flags = (TextFormatFlags.EndEllipsis | TextFormatFlags.HorizontalCenter | TextFormatFlags.SingleLine);
switch (this._style)
{
case FileTransfersItemStyle.Send:
case FileTransfersItemStyle.Receive:
if (this.CancelState != ControlState.Normal)
{
rect = this.CancelTransfersRect;
rect.Inflate(2, 2);
this.RenderBackgroundInternal(g, rect, this._baseColor, this._borderColor, innerBorderColor, RoundStyle.None, this._radius, 0.0f, true, true, LinearGradientMode.Vertical);
}
TextRenderer.DrawText(g, this.FileTransfersText.CancelTransfers, this.Font, this.CancelTransfersRect, this.ForeColor, flags);
break;
case FileTransfersItemStyle.ReadyReceive:
{
bool drawBack = false;
if (this.SaveState != ControlState.Normal)
{
rect = this.SaveRect;
rect.Inflate(2, 2);
drawBack = true;
}
if (this.SaveToState != ControlState.Normal)
{
rect = this.SaveToRect;
rect.Inflate(2, 2);
drawBack = true;
}
if (this.RefuseState != ControlState.Normal)
{
rect = this.RefuseReceiveRect;
rect.Inflate(2, 2);
drawBack = true;
}
if (drawBack)
{
this.RenderBackgroundInternal(g, rect, this._baseColor, this._borderColor, innerBorderColor, RoundStyle.None, this._radius, 0.45f, true, true, LinearGradientMode.Vertical);
}
TextRenderer.DrawText(g, this.FileTransfersText.RefuseReceive, this.Font, this.RefuseReceiveRect, this.ForeColor, flags);
TextRenderer.DrawText(g, this.FileTransfersText.SaveTo, this.Font, this.SaveToRect, this.ForeColor, flags);
TextRenderer.DrawText(g, this.FileTransfersText.Save, this.Font, this.SaveRect, this.ForeColor, flags);
break;
}
}
}
protected override void OnPaintBackground(PaintEventArgs e)
{
base.OnPaintBackground(e);
Graphics g = e.Graphics;
Rectangle rect = base.ClientRectangle;
g.SmoothingMode = SmoothingMode.AntiAlias;
rect.Inflate(-1, -1);
this.RenderBackgroundInternal(g, rect, this._baseColor, this._borderColor, Color.FromArgb(200, 255, 255), this._roundStyle, this._radius, 0.45f, true, false, LinearGradientMode.Vertical);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
if (this._timer != null)
{
this._timer.Dispose();
}
this._fileTransfersText = null;
}
}
private void SetStyles()
{
base.SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.FixedHeight | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);
base.SetStyle(ControlStyles.Opaque, false);
base.UpdateStyles();
}
internal void RenderBackgroundInternal(Graphics g, Rectangle rect, Color baseColor, Color borderColor, Color innerBorderColor, RoundStyle style, int roundWidth, float basePosition, bool drawBorder, bool drawGlass, LinearGradientMode mode)
{
if (drawBorder)
{
rect.Width--;
rect.Height--;
}
if (rect.Width > 0 && rect.Height > 0)
{
using (LinearGradientBrush brush = new LinearGradientBrush(rect, Color.Transparent, Color.Transparent, mode))
{
Color[] colors = new Color[]
{
this.GetColor(baseColor, 0, 35, 24, 9),
this.GetColor(baseColor, 0, 13, 8, 3),
baseColor,
this.GetColor(baseColor, 0, 68, 69, 54)
};
brush.InterpolationColors = new ColorBlend
{
Positions = new float[]
{
0f,
basePosition,
basePosition + 0.05f,
1f
},
Colors = colors
};
if (style != RoundStyle.None)
{
using (GraphicsPath path = GraphicsPathHelper.CreatePath(rect, roundWidth, style, false))
{
g.FillPath(brush, path);
}
if (baseColor.A > 80)
{
Rectangle rectTop = rect;
if (mode == LinearGradientMode.Vertical)
{
rectTop.Height = (int)((float)rectTop.Height * basePosition);
}
else
{
rectTop.Width = (int)((float)rect.Width * basePosition);
}
using (GraphicsPath pathTop = GraphicsPathHelper.CreatePath(rectTop, roundWidth, RoundStyle.Top, false))
{
using (SolidBrush brushAlpha = new SolidBrush(Color.FromArgb(80, 255, 255, 255)))
{
g.FillPath(brushAlpha, pathTop);
}
}
}
if (drawGlass)
{
RectangleF glassRect = rect;
if (mode == LinearGradientMode.Vertical)
{
glassRect.Y = (float)rect.Y + (float)rect.Height * basePosition;
glassRect.Height = ((float)rect.Height - (float)rect.Height * basePosition) * 2f;
}
else
{
glassRect.X = (float)rect.X + (float)rect.Width * basePosition;
glassRect.Width = ((float)rect.Width - (float)rect.Width * basePosition) * 2f;
}
this.DrawGlass(g, glassRect, 170, 0);
}
if (drawBorder)
{
using (GraphicsPath path = GraphicsPathHelper.CreatePath(rect, roundWidth, style, false))
{
using (Pen pen = new Pen(borderColor))
{
g.DrawPath(pen, path);
}
}
rect.Inflate(-1, -1);
using (GraphicsPath path = GraphicsPathHelper.CreatePath(rect, roundWidth, style, false))
{
using (Pen pen = new Pen(innerBorderColor))
{
g.DrawPath(pen, path);
}
}
}
}
else
{
g.FillRectangle(brush, rect);
if (baseColor.A > 80)
{
Rectangle rectTop = rect;
if (mode == LinearGradientMode.Vertical)
{
rectTop.Height = (int)((float)rectTop.Height * basePosition);
}
else
{
rectTop.Width = (int)((float)rect.Width * basePosition);
}
using (SolidBrush brushAlpha = new SolidBrush(Color.FromArgb(80, 255, 255, 255)))
{
g.FillRectangle(brushAlpha, rectTop);
}
}
if (drawGlass)
{
RectangleF glassRect = rect;
if (mode == LinearGradientMode.Vertical)
{
glassRect.Y = (float)rect.Y + (float)rect.Height * basePosition;
glassRect.Height = ((float)rect.Height - (float)rect.Height * basePosition) * 2f;
}
else
{
glassRect.X = (float)rect.X + (float)rect.Width * basePosition;
glassRect.Width = ((float)rect.Width - (float)rect.Width * basePosition) * 2f;
}
this.DrawGlass(g, glassRect, 200, 0);
}
if (drawBorder)
{
using (Pen pen = new Pen(borderColor))
{
g.DrawRectangle(pen, rect);
}
rect.Inflate(-1, -1);
using (Pen pen = new Pen(innerBorderColor))
{
g.DrawRectangle(pen, rect);
}
}
}
}
}
}
private void DrawGlass(Graphics g, RectangleF glassRect, int alphaCenter, int alphaSurround)
{
this.DrawGlass(g, glassRect, Color.White, alphaCenter, alphaSurround);
}
private void DrawGlass(Graphics g, RectangleF glassRect, Color glassColor, int alphaCenter, int alphaSurround)
{
using (GraphicsPath path = new GraphicsPath())
{
path.AddEllipse(glassRect);
using (PathGradientBrush brush = new PathGradientBrush(path))
{
brush.CenterColor = Color.FromArgb(alphaCenter, glassColor);
brush.SurroundColors = new Color[]
{
Color.FromArgb(alphaSurround, glassColor)
};
brush.CenterPoint = new PointF(glassRect.X + glassRect.Width / 2f, glassRect.Y + glassRect.Height / 2f);
g.FillPath(brush, path);
}
}
}
private Color GetColor(Color colorBase, int a, int r, int g, int b)
{
int a2 = (int)colorBase.A;
int r2 = (int)colorBase.R;
int g2 = (int)colorBase.G;
int b2 = (int)colorBase.B;
if (a + a2 > 255)
{
a = 255;
}
else
{
a = Math.Max(a + a2, 0);
}
if (r + r2 > 255)
{
r = 255;
}
else
{
r = Math.Max(r + r2, 0);
}
if (g + g2 > 255)
{
g = 255;
}
else
{
g = Math.Max(g + g2, 0);
}
if (b + b2 > 255)
{
b = 255;
}
else
{
b = Math.Max(b + b2, 0);
}
return Color.FromArgb(a, r, g, b);
}
private string GetText(double size)
{
string result;
if (size < 1024.0)
{
result = string.Format("{0} B", size.ToString("f1"));
}
else
{
if (size < 1048576.0)
{
result = string.Format("{0} KB", (size / 1024.0).ToString("f1"));
}
else
{
result = string.Format("{0} MB", (size / 1048576.0).ToString("f1"));
}
}
return result;
}
private string GetSpeedText()
{
TimeSpan span = DateTime.Now - this._startTime;
double speed = (double)this._totalTransfersSize / span.TotalSeconds;
return string.Format("{0}/s", this.GetText(speed));
}
private Rectangle Inflate(Rectangle rect)
{
rect.Inflate(2, 2);
return rect;
}
}
}

View File

@@ -0,0 +1,21 @@
namespace NetWorkHelper
{
/// <summary>
/// <20>ļ<EFBFBD>״̬
/// </summary>
public enum FileTransfersItemStyle
{
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD>
/// </summary>
Send,
/// <summary>
/// ׼<><D7BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD>
/// </summary>
ReadyReceive,
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD>
/// </summary>
Receive
}
}

View File

@@ -0,0 +1,34 @@
namespace NetWorkHelper
{
internal class FileTransfersItemText : IFileTransfersItemText
{
public string Save
{
get
{
return "接收";
}
}
public string SaveTo
{
get
{
return "另存为...";
}
}
public string RefuseReceive
{
get
{
return "拒绝";
}
}
public string CancelTransfers
{
get
{
return "取消";
}
}
}
}

View File

@@ -0,0 +1,47 @@
using System.Drawing;
using System.Drawing.Drawing2D;
namespace NetWorkHelper
{
public static class GraphicsPathHelper
{
public static GraphicsPath CreatePath(Rectangle rect, int radius, RoundStyle style, bool correction)
{
GraphicsPath path = new GraphicsPath();
int radiusCorrection = correction ? 1 : 0;
switch (style)
{
case RoundStyle.None:
path.AddRectangle(rect);
break;
case RoundStyle.All:
path.AddArc(rect.X, rect.Y, radius, radius, 180f, 90f);
path.AddArc(rect.Right - radius - radiusCorrection, rect.Y, radius, radius, 270f, 90f);
path.AddArc(rect.Right - radius - radiusCorrection, rect.Bottom - radius - radiusCorrection, radius, radius, 0f, 90f);
path.AddArc(rect.X, rect.Bottom - radius - radiusCorrection, radius, radius, 90f, 90f);
break;
case RoundStyle.Left:
path.AddArc(rect.X, rect.Y, radius, radius, 180f, 90f);
path.AddLine(rect.Right - radiusCorrection, rect.Y, rect.Right - radiusCorrection, rect.Bottom - radiusCorrection);
path.AddArc(rect.X, rect.Bottom - radius - radiusCorrection, radius, radius, 90f, 90f);
break;
case RoundStyle.Right:
path.AddArc(rect.Right - radius - radiusCorrection, rect.Y, radius, radius, 270f, 90f);
path.AddArc(rect.Right - radius - radiusCorrection, rect.Bottom - radius - radiusCorrection, radius, radius, 0f, 90f);
path.AddLine(rect.X, rect.Bottom - radiusCorrection, rect.X, rect.Y);
break;
case RoundStyle.Top:
path.AddArc(rect.X, rect.Y, radius, radius, 180f, 90f);
path.AddArc(rect.Right - radius - radiusCorrection, rect.Y, radius, radius, 270f, 90f);
path.AddLine(rect.Right - radiusCorrection, rect.Bottom - radiusCorrection, rect.X, rect.Bottom - radiusCorrection);
break;
case RoundStyle.Bottom:
path.AddArc(rect.Right - radius - radiusCorrection, rect.Bottom - radius - radiusCorrection, radius, radius, 0f, 90f);
path.AddArc(rect.X, rect.Bottom - radius - radiusCorrection, radius, radius, 90f, 90f);
path.AddLine(rect.X, rect.Y, rect.Right - radiusCorrection, rect.Y);
break;
}
path.CloseFigure();
return path;
}
}
}

View File

@@ -0,0 +1,22 @@
namespace NetWorkHelper
{
public interface IFileTransfersItemText
{
string Save
{
get;
}
string SaveTo
{
get;
}
string RefuseReceive
{
get;
}
string CancelTransfers
{
get;
}
}
}

View File

@@ -0,0 +1,12 @@
namespace NetWorkHelper
{
public enum RoundStyle
{
None,
All,
Left,
Right,
Top,
Bottom
}
}

View File

@@ -0,0 +1,37 @@
using System;
namespace NetWorkHelper
{
[Serializable]
public class TraFransfersFile
{
private string _md5;
private int _index;
private byte[] _buffer;
public TraFransfersFile(string md5, int index, byte[] buffer)
{
_md5 = md5;
_index = index;
_buffer = buffer;
}
public string MD5
{
get { return _md5; }
set { _md5 = value; }
}
public int Index
{
get { return _index; }
set { _index = value; }
}
public byte[] Buffer
{
get { return _buffer; }
set { _buffer = value; }
}
}
}

View File

@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="toolTip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>

View File

@@ -0,0 +1,68 @@
using System;
using System.Drawing;
namespace NetWorkHelper
{
[Serializable]
public class TraFransfersFileStart
{
private string _md5;
private string _fileName;
private Image _image;
private long _length;
private long _partCount;
private int _partSize;
public TraFransfersFileStart(
string md5,
string fileName,
Image image,
long length,
long partCount,
int partSize)
{
_md5 = md5;
_fileName = fileName;
_image = image;
_length = length;
_partCount = partCount;
_partSize = partSize;
}
public string MD5
{
get { return _md5; }
set { _md5 = value; }
}
public Image Image
{
get { return _image; }
set { _image = value; }
}
public string FileName
{
get { return _fileName; }
set { _fileName = value; }
}
public long Length
{
get { return _length; }
set { _length = value; }
}
public long PartCount
{
get { return _partCount; }
set { _partCount = value; }
}
public int PartSize
{
get { return _partSize; }
set { _partSize = value; }
}
}
}

View File

@@ -0,0 +1,20 @@
using System;
namespace NetWorkHelper
{
public delegate void FileReceiveBufferEventHandler(object sender, FileReceiveBufferEventArgs e);
public class FileReceiveBufferEventArgs : EventArgs
{
public FileReceiveBufferEventArgs(ReceiveFileManager receiveFileManager, int size)
: base()
{
ReceiveFileManager = receiveFileManager;
Size = size;
}
public ReceiveFileManager ReceiveFileManager { get; }
public int Size { get; }
}
}

View File

@@ -0,0 +1,19 @@
using System;
namespace NetWorkHelper
{
public delegate void FileReceiveCompleteEventHandler(object sender, FileReceiveCompleteEventArgs e);
public class FileReceiveCompleteEventArgs : EventArgs
{
public FileReceiveCompleteEventArgs() { }
public FileReceiveCompleteEventArgs(bool success)
: base()
{
Success = success;
}
public bool Success { get; set; }
}
}

View File

@@ -0,0 +1,20 @@
using System;
namespace NetWorkHelper
{
public delegate void FileReceiveEventHandler(object sender, FileReceiveEventArgs e);
public class FileReceiveEventArgs : EventArgs
{
public FileReceiveEventArgs() { }
public FileReceiveEventArgs(ReceiveFileManager receiveFileManager) : base()
{
ReceiveFileManager = receiveFileManager;
}
public ReceiveFileManager ReceiveFileManager { get; }
public object Tag { get; set; }
}
}

View File

@@ -0,0 +1,20 @@
using System;
namespace NetWorkHelper
{
public delegate void FileSendBufferEventHandler(object sender, FileSendBufferEventArgs e);
public class FileSendBufferEventArgs : EventArgs
{
public FileSendBufferEventArgs(SendFileManager sendFileManager, int size)
: base()
{
SendFileManager = sendFileManager;
Size = size;
}
public SendFileManager SendFileManager { get; }
public int Size { get; }
}
}

View File

@@ -0,0 +1,17 @@
using System;
namespace NetWorkHelper
{
public delegate void FileSendEventHandler(object sender, FileSendEventArgs e);
public class FileSendEventArgs : EventArgs
{
public FileSendEventArgs(SendFileManager sendFileManager)
: base()
{
SendFileManager = sendFileManager;
}
public SendFileManager SendFileManager { get; }
}
}

View File

@@ -0,0 +1,20 @@
using System;
namespace NetWorkHelper
{
public delegate void ReadFileBufferEventHandler(object sender, ReadFileBufferEventArgs e);
public class ReadFileBufferEventArgs : EventArgs
{
public ReadFileBufferEventArgs(int index, byte[] buffer)
: base()
{
Index = index;
Buffer = buffer;
}
public int Index { get; }
public byte[] Buffer { get; }
}
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Net;
namespace NetWorkHelper
{
public delegate void ReceiveDataEventHandler(object sender, ReceiveDataEventArgs e);
public class ReceiveDataEventArgs : EventArgs
{
public ReceiveDataEventArgs() { }
public ReceiveDataEventArgs(byte[] buffer, IPEndPoint remoteIP)
: base()
{
Buffer = buffer;
RemoteIP = remoteIP;
}
public byte[] Buffer { get; set; }
public IPEndPoint RemoteIP { get; set; }
}
}

View File

@@ -0,0 +1,35 @@
using System.ComponentModel;
using System.Net;
namespace NetWorkHelper
{
public delegate void RequestSendFileEventHandler(object sender, RequestSendFileEventArgs e);
public class RequestSendFileEventArgs : CancelEventArgs
{
public RequestSendFileEventArgs()
: base()
{
}
public RequestSendFileEventArgs(TraFransfersFileStart traFransfersFileStart, IPEndPoint remoteIP)
: base()
{
TraFransfersFileStart = traFransfersFileStart;
RemoteIP = remoteIP;
}
public RequestSendFileEventArgs(TraFransfersFileStart traFransfersFileStart, IPEndPoint remoteIP, bool cancel)
: base(cancel)
{
TraFransfersFileStart = traFransfersFileStart;
RemoteIP = remoteIP;
}
public IPEndPoint RemoteIP { get; set; }
public TraFransfersFileStart TraFransfersFileStart { get; set; }
public string Path { get; set; }
}
}

View File

@@ -0,0 +1,12 @@
namespace NetWorkHelper
{
/// <summary>
/// 消息数据单元接口
/// </summary>
public interface IDataCell
{
byte[] ToBuffer();
void FromBuffer(byte[] buffer);
}
}

View File

@@ -0,0 +1,16 @@

namespace NetWorkHelper
{
internal class ReadFileObject
{
public ReadFileObject(int index, byte[] buffer)
{
Index = index;
Buffer = buffer;
}
public int Index { get; set; }
public byte[] Buffer { get; set; }
}
}

View File

@@ -0,0 +1,238 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
namespace NetWorkHelper
{
public class ReceiveFileManager : IDisposable
{
#region Fields
private string _path;
private string _tempFileName;
private string _fullName;
private int _partSize;
private long _length;
private FileStream _fileStream;
private DateTime _lastReceiveTime;
private Timer _timer;
private int _interval = 5000;
private long _receivePartCount;
private static object SyncLock = new object();
private static readonly int ReceiveTimeout = 5000;
private static readonly string FileTemptName = ".tmp";
#endregion
#region Constructors
public ReceiveFileManager() { }
public ReceiveFileManager(string md5, string path, string fileName, long partCount, int partSize, long length, IPEndPoint remoteIP)
{
MD5 = md5;
_path = path;
Name = fileName;
PartCount = partCount;
_partSize = partSize;
_length = length;
RemoteIP = remoteIP;
Create();
}
#endregion
#region Events
public event FileReceiveCompleteEventHandler ReceiveFileComplete;
public event EventHandler ReceiveFileTimeout;
#endregion
#region Properties
public string MD5 { get; }
public long PartCount { get; }
public string Name { get; }
public string FileName
{
get
{
if (string.IsNullOrEmpty(_fullName))
{
GetFileName();
}
return _fullName;
}
}
public object Tag { get; set; }
public bool Success { get; private set; }
public IPEndPoint RemoteIP { get; }
public bool Completed
{
get { return PartCount == _receivePartCount; }
}
private Stream FileStream { get; set; }
private Dictionary<int, bool> ReceiveFilePartList { get; set; }
private Timer Timer
{
get
{
if (_timer == null)
{
_timer = new Timer(
new TimerCallback(delegate (object obj)
{
TimeSpan ts = DateTime.Now - _lastReceiveTime;
if (ts.TotalMilliseconds > ReceiveTimeout)
{
_lastReceiveTime = DateTime.Now;
OnReceiveFileTimeout(EventArgs.Empty);
}
}),
null,
Timeout.Infinite,
_interval);
}
return _timer;
}
}
#endregion
#region Methods
private void Create()
{
_tempFileName = string.Format("{0}\\{1}{2}", _path, Name, FileTemptName);
_fileStream = new FileStream(_tempFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, _partSize * 10, true);
FileStream = Stream.Synchronized(_fileStream);
ReceiveFilePartList = new Dictionary<int, bool>();
for (int i = 0; i < PartCount; i++)
{
ReceiveFilePartList.Add(i, false);
}
}
public void Start()
{
_lastReceiveTime = DateTime.Now;
Timer.Change(0, _interval);
}
public int GetNextReceiveIndex()
{
foreach (int index in ReceiveFilePartList.Keys)
{
if (ReceiveFilePartList[index] == false)
{
return index;
}
}
return -1;
}
public int ReceiveBuffer(int index, byte[] buffer)
{
_lastReceiveTime = DateTime.Now;
if (ReceiveFilePartList[index])
{
return 0;
}
else
{
lock (SyncLock)
{
ReceiveFilePartList[index] = true;
_receivePartCount++;
}
FileStream.Position = index * _partSize;
FileStream.BeginWrite(buffer, 0, buffer.Length, new AsyncCallback(EndWrite), _receivePartCount);
return buffer.Length;
}
}
protected virtual void OnReceiveFileComplete(FileReceiveCompleteEventArgs e)
{
ReceiveFileComplete?.Invoke(this, e);
}
protected virtual void OnReceiveFileTimeout(EventArgs e)
{
ReceiveFileTimeout?.Invoke(this, e);
}
private void EndWrite(IAsyncResult result)
{
if (FileStream == null)
{
return;
}
FileStream.EndWrite(result);
long index = (long)result.AsyncState;
if (index == PartCount)
{
Dispose();
File.Move(_tempFileName, FileName);
Success = MD5 == MD5Helper.CretaeMD5(FileName);
OnReceiveFileComplete(new FileReceiveCompleteEventArgs(Success));
}
}
private void GetFileName()
{
_fullName = string.Format("{0}\\{1}", _path, Name);
int nameIndex = 1;
int index = Name.LastIndexOf('.');
while (File.Exists(_fullName))
{
_fullName = string.Format("{0}\\{1}", _path, Name.Insert(index, nameIndex.ToString("_0")));
nameIndex++;
}
}
#endregion
#region IDisposable
public void Dispose()
{
if (_timer != null)
{
_timer.Dispose();
_timer = null;
}
if (_fileStream != null)
{
FileStream.Flush();
FileStream.Close();
FileStream.Dispose();
FileStream = null;
_fileStream = null;
}
if (ReceiveFilePartList != null)
{
ReceiveFilePartList.Clear();
ReceiveFilePartList = null;
}
}
#endregion
}
}

View File

@@ -0,0 +1,152 @@
using System;
using System.IO;
namespace NetWorkHelper
{
/// <summary>
/// 文件管理类
/// </summary>
public class SendFileManager : IDisposable
{
#region
private FileStream _fileStream;
#endregion
#region
public SendFileManager(string fileName)
{
FileName = fileName;
Create(fileName);
}
public SendFileManager(string fileName, int partSize)
{
FileName = fileName;
PartSize = partSize;
Create(fileName);
}
#endregion
#region
public long PartCount { get; set; }
public long Length { get; private set; }
public int PartSize { get; } = 1024 * 20;
public string FileName { get; }
public string Name
{
get { return new FileInfo(FileName).Name; }
}
public string MD5 { get; private set; }
public object Tag { get; set; }
internal Stream FileStream { get; private set; }
#endregion
#region
/// <summary>
/// 创建初始化文件管理类
/// </summary>
/// <param name="fileName">文件路径</param>
private void Create(string fileName)
{
_fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, PartSize * 10, true);
FileStream = Stream.Synchronized(_fileStream);
Length = _fileStream.Length;
PartCount = Length / PartSize;
if (Length % PartSize != 0)
{
PartCount++;
}
MD5 = MD5Helper.CretaeMD5(_fileStream);
}
/// <summary>
/// 读取文件
/// </summary>
/// <param name="index"></param>
public void Read(int index)
{
int size = PartSize;
if (Length - PartSize * index < PartSize)
{
size = (int)(Length - PartSize * index);
}
byte[] buffer = new byte[size];
ReadFileObject obj = new ReadFileObject(index, buffer);
FileStream.Position = index * PartSize;
FileStream.BeginRead(buffer, 0, size, new AsyncCallback(EndRead), obj);
}
/// <summary>
/// 结束读取文件
/// </summary>
/// <param name="result"></param>
private void EndRead(IAsyncResult result)
{
if (FileStream == null)
{
return;
}
int length = FileStream.EndRead(result);
ReadFileObject state = (ReadFileObject)result.AsyncState;
int index = state.Index;
byte[] buffer = state.Buffer;
ReadFileBufferEventArgs e = null;
if (length < PartSize)
{
byte[] realBuffer = new byte[length];
Buffer.BlockCopy(buffer, 0, realBuffer, 0, length);
e = new ReadFileBufferEventArgs(index, realBuffer);
}
else
{
e = new ReadFileBufferEventArgs(index, buffer);
}
OnReadFileBuffer(e);
}
#endregion
#region
/// <summary>
/// 读取文件事件
/// </summary>
public event ReadFileBufferEventHandler ReadFileBuffer;
/// <summary>
/// 读取文件方法
/// </summary>
/// <param name="e"></param>
protected void OnReadFileBuffer(ReadFileBufferEventArgs e)
{
ReadFileBuffer?.Invoke(this, e);
}
#endregion
#region IDisposable
public void Dispose()
{
if (_fileStream != null)
{
FileStream.Flush();
FileStream.Close();
FileStream.Dispose();
FileStream = null;
_fileStream = null;
}
}
#endregion
}
}

View File

@@ -0,0 +1,65 @@
using System;
namespace NetWorkHelper
{
/// <summary>
/// 消息单元类(可序列化)
/// </summary>
[Serializable]
public class MsgCell : IDataCell
{
/// <summary>
/// 消息标识
/// </summary>
public int MessageId { get; set; }
private object _data;
/// <summary>
/// 消息序列化数据
/// </summary>
public object Data
{
get { return _data; }
set { _data = value; }
}
#region
public MsgCell() { }
/// <summary>
/// 构造函数
/// </summary>
/// <param name="messageId">消息标识</param>
/// <param name="data">序列化数据</param>
public MsgCell(
int messageId,
object data)
{
MessageId = messageId;
_data = data;
}
#endregion
/// <summary>
/// 将数据序列化成Byte[]数组
/// </summary>
/// <returns></returns>
public byte[] ToBuffer()
{
byte[] data = SerHelper.Serialize(_data);
byte[] id = BitConverter.GetBytes(MessageId);
byte[] buffer = new byte[data.Length + id.Length];
Buffer.BlockCopy(id, 0, buffer, 0, id.Length);
Buffer.BlockCopy(data, 0, buffer, id.Length, data.Length);
return buffer;
}
/// <summary>
/// 将Byte[]数组反序列化成数据结构
/// </summary>
/// <param name="buffer"></param>
public void FromBuffer(byte[] buffer)
{
MessageId = BitConverter.ToInt32(buffer, 0);
_data = SerHelper.Deserialize(buffer, 4);
}
}
}

View File

@@ -0,0 +1,39 @@
using System;
namespace NetWorkHelper
{
[Serializable]
public class MsgTypeCell
{
private MsgType _msgType;
private string _imageSuffix = "";
private byte[] _bufferBytes;
/// <summary>
/// 消息类型
/// </summary>
public MsgType Msgtype
{
get { return _msgType; }
set { _msgType = value; }
}
/// <summary>
/// 图片后缀格式
/// </summary>
public string ImageSuffix
{
get { return _imageSuffix; }
set { _imageSuffix = value; }
}
public byte[] BufferBytes
{
get { return _bufferBytes; }
set { _bufferBytes = value; }
}
public MsgTypeCell(MsgType msgType, byte[] buffer)
{
Msgtype = msgType;
BufferBytes = buffer;
}
}
}

View File

@@ -0,0 +1,39 @@
using System;
namespace NetWorkHelper
{
[Serializable]
public class ResponeTraFransfersFile
{
private string _md5;
private int _size;
private int _index;
public ResponeTraFransfersFile() { }
public ResponeTraFransfersFile(string md5, int size, int index)
{
_md5 = md5;
_size = size;
_index = index;
}
public string MD5
{
get { return _md5; }
set { _md5 = value; }
}
public int Size
{
get { return _size; }
set { _size = value; }
}
public int Index
{
get { return _index; }
set { _index = value; }
}
}
}

View File

@@ -0,0 +1,201 @@
using System;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
namespace NetWorkHelper
{
public class UdpLibrary : IDisposable
{
#region
public UdpLibrary(int port)
{
Port = port;
}
public UdpLibrary()
{
//默认监听端口1234
Port = 1234;
}
#endregion
#region
private UdpClient _udpClient;
private bool _started;
#endregion
#region
[Description("UDP监听端口")]
[Category("UDP服务端")]
public int Port { get; set; } = 1234;
[Description("UDP客户端")]
[Category("UDP服务端")]
internal UdpClient UdpClient
{
get
{
if (_udpClient == null)
{
bool success = false;
while (!success)
{
try
{
_udpClient = new UdpClient(Port);
success = true;
}
catch (SocketException ex)
{
Port++;
if (Port > 65535)
{
success = true;
throw ex;
}
}
}
uint IOC_IN = 0x80000000;
uint IOC_VENDOR = 0x18000000;
uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
_udpClient.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
}
return _udpClient;
}
}
#endregion
#region
public void Start()
{
if (!_started)
{
_started = true;
ReceiveInternal();
}
}
public void Stop()
{
try
{
_started = false;
UdpClient.Close();
_udpClient = null;
}
catch
{
}
}
public void Send(IDataCell cell, IPEndPoint remoteIP)
{
byte[] buffer = cell.ToBuffer();
SendInternal(buffer, remoteIP);
}
public void Send(byte[] buffer, IPEndPoint remoteIP)
{
SendInternal(buffer, remoteIP);
}
protected void SendInternal(byte[] buffer, IPEndPoint remoteIP)
{
if (!_started)
{
throw new ApplicationException("UDP Closed.");
}
try
{
UdpClient.BeginSend(buffer, buffer.Length, remoteIP, new AsyncCallback(SendCallback), null);
}
catch (SocketException ex)
{
throw ex;
}
}
public bool IsStarted()
{
return _started;
}
protected void ReceiveInternal()
{
if (!_started)
{
return;
}
try
{
UdpClient.BeginReceive(new AsyncCallback(ReceiveCallback), null);
}
catch (SocketException ex)
{
//_started = false;
throw ex;
}
}
void SendCallback(IAsyncResult result)
{
try
{
UdpClient.EndSend(result);
}
catch (SocketException ex)
{
throw ex;
}
}
void ReceiveCallback(IAsyncResult result)
{
if (!_started)
{
return;
}
IPEndPoint remoteIP = new IPEndPoint(IPAddress.Any, 0);
byte[] buffer = null;
try
{
buffer = UdpClient.EndReceive(result, ref remoteIP);
}
catch (SocketException ex)
{
throw ex;
}
finally
{
ReceiveInternal();
}
OnReceiveData(new ReceiveDataEventArgs(buffer, remoteIP));
}
#endregion
#region IDisposable
public void Dispose()
{
_started = false;
if (_udpClient != null)
{
_udpClient.Close();
_udpClient = null;
}
}
#endregion
#region
public event ReceiveDataEventHandler ReceiveData;
[Description("UDP服务端接收数据事件")]
[Category("UDPServer事件")]
protected virtual void OnReceiveData(ReceiveDataEventArgs e)
{
ReceiveData?.Invoke(this, e);
}
#endregion
}
}

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,36 @@
namespace NetWorkHelper.TCP
{
partial class ITcpClient
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

View File

@@ -0,0 +1,624 @@
using NetWorkHelper.ICommond;
using NetWorkHelper.IModels;
using System;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace NetWorkHelper.TCP
{
public partial class ITcpClient : Component
{
//#region 读取ini文件
//[DllImport("kernel32")]
//private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
///// <summary>
///// 读出INI文件
///// </summary>
///// <param name="Section">项目名称(如 [TypeName] )</param>
///// <param name="Key">键</param>
//public string IniReadValue(string Section, string Key)
//{
// StringBuilder temp = new StringBuilder(500);
// int i = GetPrivateProfileString(Section, Key, "", temp, 500, System.AppDomain.CurrentDomain.BaseDirectory + "MESConfig.ini");
// return temp.ToString();
//}
static int connecttimeout = 4000;
static int receivetimeout = 2000;
//static int sleeptime;
static int timeoutsend = 3;
//public void ReadINI()
//{
// //string dialog;
// //dialog = System.AppDomain.CurrentDomain.BaseDirectory + "MESConfig.ini";
// //ControlINI mesconfig = new ControlINI(dialog);
// //连接设置
// connecttimeout = Convert.ToInt32(IniReadValue("MESConfig", "connectTimeout")); ;
// receivetimeout = Convert.ToInt32(IniReadValue("MESConfig", "receiveTimeout"));
// _reConnectTime = Convert.ToInt32(IniReadValue("MESConfig", "sleepTime"));
// timeoutsend = Convert.ToInt32(IniReadValue("MESConfig", "timeoutSend"))+1;
//}
//#endregion
#region
public ITcpClient()
{
//ReadINI();
InitializeComponent();
}
public ITcpClient(IContainer container)
{
container.Add(this);
InitializeComponent();
}
#endregion
#region
public IClient Client = null;
private Thread _startThread = null;
private int _reConnectCount = 0;//重连计数
private int _maxConnectCount => timeoutsend;
private ConncetType _conncetType = ConncetType.Conncet;
private bool _isReconnect = true;//是否开启断开重连
private int _reConnectTime;//重连间隔时间
private bool _isStart = false;// 是否启动
private System.Timers.Timer _timer = new System.Timers.Timer(); // 连接后两秒未成功重连
//bool timeoutreconnected=true;//连接超时的重连
//bool datareconnected = true;//接收不到心跳包的重连
#endregion
#region
/// <summary>
/// 服务端IP
/// </summary>
private string _serverip = "127.0.0.1";
[Description("服务端IP")]
[Category("TCP客户端")]
public string ServerIp
{
set { _serverip = value; }
get { return _serverip; }
}
/// <summary>
/// 服务端监听端口
/// </summary>
private int _serverport = 5000;
[Description("服务端监听端口")]
[Category("TCP客户端")]
public int ServerPort
{
set { _serverport = value; }
get { return _serverport; }
}
/// <summary>
/// 网络端点
/// </summary>
private IPEndPoint _ipEndPoint = null;
[Description("网络端点,IP+PORT")]
[Category("TCP客户端")]
internal IPEndPoint IpEndPoint
{
get
{
try
{
IPAddress ipAddress = null;
ipAddress = string.IsNullOrEmpty(ServerIp)
? IPAddress.Any
: IPAddress.Parse(CommonMethod.HostnameToIp(ServerIp));
_ipEndPoint = new IPEndPoint(ipAddress, ServerPort);
}
catch
{
}
return _ipEndPoint;
}
}
/// <summary>
/// 是否重连
/// </summary>
[Description("是否重连")]
[Category("TCP客户端")]
public bool IsReconnection
{
set { _isReconnect = value; }
get { return _isReconnect; }
}
/// <summary>
/// 设置断开重连时间间隔单位毫秒默认3000毫秒
/// </summary>
[Description("设置断开重连时间间隔单位毫秒默认3000毫秒")]
[Category("TCP客户端")]
public int ReConnectionTime
{
get { return _reConnectTime; }
set { _reConnectTime = value; }
}
[Description("设置断开重连时间间隔单位毫秒默认3000毫秒")]
[Category("TCP客户端"), Browsable(false)]
public bool IsStart
{
get { return _isStart; }
set { _isStart = value; }
}
#endregion
#region
private readonly object _threadLock = new object();
public void StartConnect()
{
if (IsStart)
return;
lock (_threadLock)
{
if (_startThread == null || !_startThread.IsAlive)
{
_startThread = new Thread(StartThread);
_startThread.IsBackground = true;
_startThread.Start();
}
}
}
/// <summary>
/// 启动客户端基础的一个线程
/// </summary>
private void StartThread()
{
if (_conncetType == ConncetType.ReConncet && IsReconnection && !IsStart) //如果是重连的延迟N秒
{
Thread.Sleep(ReConnectionTime);
if (IsReconnection)
{
TcpClientStateInfo(string.Format("正在重连..."), SocketState.Reconnection);
}
try
{
_timer.Interval = connecttimeout;
_timer.Elapsed += Timer_Elapsed;
_timer.AutoReset = false;
_timer.Start();
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.ReceiveTimeout = receivetimeout;
socket.SendTimeout = 1000;
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true);
socket.BeginConnect(IpEndPoint, new AsyncCallback(AcceptCallback), socket);
//timeoutreconnected = true;//连接超时的重连
//datareconnected = true;//接收不到心跳包的重连
}
catch (Exception ex)
{
_timer.Stop();
TcpClientErrorMsg(string.Format("连接服务器失败,错误原因:{0},行号{1}", ex.Message, ex.StackTrace));
if (IsReconnection)
{
Reconnect();
}
}
}
else if (!IsStart)
{
if (IsReconnection)
{
TcpClientStateInfo("正在连接服务器... ...", SocketState.Connecting);
try
{
_timer.Interval = connecttimeout;
_timer.Elapsed += Timer_Elapsed;
_timer.AutoReset = false;
_timer.Start();
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.ReceiveTimeout = receivetimeout;
socket.SendTimeout = 1000;
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true);
socket.BeginConnect(IpEndPoint, new AsyncCallback(AcceptCallback), socket);
//timeoutreconnected = true;//连接超时的重连
//datareconnected = true;//接收不到心跳包的重连
}
catch (Exception ex)
{
_timer.Stop();
TcpClientErrorMsg(string.Format("连接服务器失败,错误原因:{0},行号{1}", ex.Message, ex.StackTrace));
if (IsReconnection)
{
Reconnect();
}
}
}
}
}
//连接超时则重新连接
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (IsReconnection)
{
//datareconnected = false;//接收不到心跳包的重连
TcpClientErrorMsg(string.Format("连接服务器失败"));
//if (Client != null)
//{
// ShutdownClient(Client);
// Client.WorkSocket.Close();
//}
Reconnect();
//reconnected = false;
}
}
/// <summary>
/// 当连接服务器之后的回调函数
/// </summary>
/// <param name="ar">TcpClient</param>
private void AcceptCallback(IAsyncResult ar)
{
_timer.Stop();
try
{
IsStart = true;
Socket socket = (Socket)ar.AsyncState;
socket.EndConnect(ar);
Client = new IClient(socket);
Client.WorkSocket.BeginReceive(Client.BufferInfo.ReceivedBuffer, 0, Client.BufferInfo.ReceivedBuffer.Length, 0, new AsyncCallback(ReadCallback), Client);
_conncetType = ConncetType.Conncet;
TcpClientStateInfo(string.Format("已连接服务器"), SocketState.Connected);
_reConnectCount = 0;
//timeoutreconnected = false;//连接超时的重连
//datareconnected = false;//接收不到心跳包的重连
}
catch (SocketException ex)
{
IsStart = false;
string msg = ex.Message;
if (ex.NativeErrorCode.Equals(10060))
{
//无法连接目标主机
msg = string.Format("{0} 无法连接: error code {1}!", "", ex.NativeErrorCode);
}
else if (ex.NativeErrorCode.Equals(10061))
{
msg = string.Format("{0} 主动拒绝正在重连: error code {1}!", "", ex.NativeErrorCode);
}
else if (ex.NativeErrorCode.Equals(10053))
{
//读写时主机断开
msg = string.Format("{0} 主动断开连接: error code {1}! ", "", ex.NativeErrorCode);
}
else
{
//其他错误
msg = string.Format("Disconnected: error code {0}!", ex.NativeErrorCode);
}
if (IsReconnection)
{
TcpClientErrorMsg(string.Format("连接服务器失败,错误原因:{0}", msg));
Reconnect();
}
}
catch (Exception ex)
{
}
}
#endregion
#region
/// <summary>
/// 重连模块
/// </summary>
private void Reconnect()
{
if (Client != null)
{
ShutdownClient(Client);
Client?.WorkSocket?.Close();
Client = null;
}
if (_conncetType == ConncetType.Conncet)
{
TcpClientStateInfo(string.Format("已断开服务器{0}", IsReconnection ? ",准备重连" : ""), SocketState.Disconnect);
}
if (!IsReconnection)
{
return;
}
_reConnectCount++;//每重连一次重连的次数加1
if (_conncetType == ConncetType.Conncet)
{
_conncetType = ConncetType.ReConncet;
//CommonMethod.EventInvoket(() => { ReconnectionStart(); });
}
_isStart = false;
if (_startThread != null)
{
try
{
// 检查线程状态,避免重复启动
if (_startThread.IsAlive)
{
// 给线程一个机会正常结束
if (!_startThread.Join(500)) // 等待500毫秒
{
try
{
_startThread.Abort(); // 强制终止
}
catch (ThreadStateException)
{
// 线程可能已经终止,忽略此异常
}
}
}
}
catch (Exception ex)
{
// 记录异常但不阻止重连
Console.WriteLine($"清理线程时异常: {ex.Message}");
}
finally
{
_startThread = null; // 确保设置为null
}
}
if (_reConnectCount < _maxConnectCount && IsReconnection)
{
StartConnect();
}
else
{
_timer.Stop();
StopConnect();
this.IsReconnection = false;
_reConnectCount = 0;
TcpClientStateInfo(string.Format("超过最大重连数,已断开服务器连接"), SocketState.Disconnect);
}
}
#endregion
#region
public void SendData(byte[] data)
{
try
{
if (data == null || data.Length == 0)
{
return;
}
if (Client != null && Client.WorkSocket != null && Client.WorkSocket.Connected)
{
//异步发送数据
//cModel.ClientSocket.Send(data);
Client.WorkSocket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), Client);
//timeoutreconnected = false;//连接超时的重连
//datareconnected = true;//接收不到心跳包的重连
}
}
catch (SocketException ex)
{
TcpClientErrorMsg(string.Format("向服务端发送数据时发生错误,错误原因:{0},行号{1}", ex.Message, ex.StackTrace));
}
}
public bool IsConnected
{
get
{
try
{
return Client != null &&
Client.WorkSocket != null &&
Client.WorkSocket.Connected;
}
catch
{
return false;
}
}
}
/// <summary>
/// 发送完数据之后的回调函数
/// </summary>
/// <param name="ar">Clicent</param>
private void SendCallback(IAsyncResult ar)
{
IClient iClient = (IClient)ar.AsyncState;
if (iClient == null)
return;
Socket handler = iClient.WorkSocket;
try
{
int bytesSent = handler.EndSend(ar);
}
catch (Exception ex)
{
TcpClientErrorMsg(string.Format("发送数据后回调时发生错误,错误原因:{0},行号{1}", ex.Message, ex.StackTrace));
}
}
#endregion
#region
/// <summary>
/// 当接收到数据之后的回调函数
/// </summary>
/// <param name="ar"></param>
private void ReadCallback(IAsyncResult ar)
{
if (Client == null || !_isStart)
return;
Socket handler = Client.WorkSocket;
try
{
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0 && bytesRead <= Client.BufferInfo.ReceivedBuffer.Length)
{
byte[] bytes = new byte[bytesRead];
Array.Copy(Client.BufferInfo.ReceivedBuffer, 0, bytes, 0, bytesRead);
TcpClientRecevice(bytes);
handler.BeginReceive(Client.BufferInfo.ReceivedBuffer, 0, Client.BufferInfo.ReceivedBuffer.Length,
0, new AsyncCallback(ReadCallback), Client);
}
else
{
if (IsReconnection)
{
Reconnect();
}
}
}
catch (Exception ex)
{
//if (datareconnected)
//{
// timeoutreconnected = false;//连接超时的重连
////IsStart = false;
StopConnect();
TcpClientErrorMsg(string.Format("接收数据失败,错误原因:{0},行号{1}", ex.Message, ex.StackTrace));
Reconnect();
//}
}
}
#endregion
#region
/// <summary>
/// 关闭相连的scoket以及关联的StateObject,释放所有的资源
/// </summary>
public void StopConnect()
{
IsStart = false;
if (Client != null)
{
var workSocket = Client.WorkSocket; // 提前保存引用
ShutdownClient(Client);
workSocket?.Close();
//if (Client.WorkSocket != null)
//{
// Client.WorkSocket.Close();
// //Client.WorkSocket?.Dispose();
//}
}
_conncetType = ConncetType.Conncet;
_reConnectCount = 0;//前面三个初始化
}
public void ShutdownClient(IClient iClient)
{
try
{
iClient.WorkSocket.Shutdown(SocketShutdown.Both);
}
catch
{
}
}
#endregion
#region
#region OnRecevice接收数据事件
[Description("接收数据事件")]
[Category("TcpClient事件")]
public event EventHandler<TcpClientReceviceEventArgs> OnRecevice;
protected virtual void TcpClientRecevice(byte[] data)
{
if (OnRecevice != null)
CommonMethod.EventInvoket(() => { OnRecevice(this, new TcpClientReceviceEventArgs(data)); });
}
#endregion
#region OnErrorMsg返回错误消息事件
[Description("返回错误消息事件")]
[Category("TcpClient事件")]
public event EventHandler<TcpClientErrorEventArgs> OnErrorMsg;
protected virtual void TcpClientErrorMsg(string msg)
{
if (OnErrorMsg != null)
CommonMethod.EventInvoket(() => { OnErrorMsg(this, new TcpClientErrorEventArgs(msg)); });
}
#endregion
#region OnStateInfo连接状态改变时返回连接状态事件
[Description("连接状态改变时返回连接状态事件")]
[Category("TcpClient事件")]
public event EventHandler<TcpClientStateEventArgs> OnStateInfo;
protected virtual void TcpClientStateInfo(string msg, SocketState state)
{
if (OnStateInfo != null)
CommonMethod.EventInvoket(() => { OnStateInfo(this, new TcpClientStateEventArgs(msg, state)); });
}
#endregion
#endregion
}
public enum ConncetType
{
Conncet,
ReConncet,
DisConncet
}
}

View File

@@ -0,0 +1,4 @@
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]

View File

@@ -0,0 +1 @@
fd1470a5ec7772d60dcf67497416fa5a98dbb5cca52c0adfcc1db2697f2a8034

View File

@@ -0,0 +1,159 @@
D:\桌面\莫禧亮\华勤\28-双通道\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.cs
D:\桌面\莫禧亮\华勤\28-双通道\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.Designer.cs
D:\桌面\莫禧亮\华勤\28-双通道\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\华勤\28-双通道\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\华勤\28-双通道\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.AssemblyReference.cache
D:\桌面\莫禧亮\华勤\28-双通道\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.AxUdpClient.resources
D:\桌面\莫禧亮\华勤\28-双通道\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.GenerateResource.cache
D:\桌面\莫禧亮\华勤\28-双通道\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.CoreCompileInputs.cache
D:\桌面\莫禧亮\华勤\28-双通道\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\华勤\28-双通道\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.pdb
C:\Users\Administrator\Desktop\备份\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.cs
C:\Users\Administrator\Desktop\备份\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.Designer.cs
C:\Users\Administrator\Desktop\备份\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.dll
C:\Users\Administrator\Desktop\备份\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.pdb
C:\Users\Administrator\Desktop\备份\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.AssemblyReference.cache
C:\Users\Administrator\Desktop\备份\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.AxUdpClient.resources
C:\Users\Administrator\Desktop\备份\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.GenerateResource.cache
C:\Users\Administrator\Desktop\备份\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.CoreCompileInputs.cache
C:\Users\Administrator\Desktop\备份\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.dll
C:\Users\Administrator\Desktop\备份\LL-28_guanghongshuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.pdb
C:\Users\Administrator\Desktop\备份\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.cs
C:\Users\Administrator\Desktop\备份\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.Designer.cs
C:\Users\Administrator\Desktop\备份\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.dll
C:\Users\Administrator\Desktop\备份\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.pdb
C:\Users\Administrator\Desktop\备份\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.AxUdpClient.resources
C:\Users\Administrator\Desktop\备份\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.GenerateResource.cache
C:\Users\Administrator\Desktop\备份\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.CoreCompileInputs.cache
C:\Users\Administrator\Desktop\备份\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.dll
C:\Users\Administrator\Desktop\备份\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.pdb
D:\上位机\备份\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.cs
D:\上位机\备份\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.Designer.cs
D:\上位机\备份\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.dll
D:\上位机\备份\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.pdb
D:\上位机\备份\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.AxUdpClient.resources
D:\上位机\备份\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.GenerateResource.cache
D:\上位机\备份\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.CoreCompileInputs.cache
D:\上位机\备份\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.dll
D:\上位机\备份\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.pdb
D:\上位机\备份\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.AssemblyReference.cache
E:\备份\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.cs
E:\备份\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.Designer.cs
E:\备份\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.dll
E:\备份\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.pdb
E:\备份\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.AssemblyReference.cache
E:\备份\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.AxUdpClient.resources
E:\备份\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.GenerateResource.cache
E:\备份\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.CoreCompileInputs.cache
E:\备份\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.dll
E:\备份\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\华勤\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.cs
D:\桌面\莫禧亮\华勤\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.Designer.cs
D:\桌面\莫禧亮\华勤\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\华勤\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\华勤\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.AssemblyReference.cache
D:\桌面\莫禧亮\华勤\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.AxUdpClient.resources
D:\桌面\莫禧亮\华勤\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.GenerateResource.cache
D:\桌面\莫禧亮\华勤\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.CoreCompileInputs.cache
D:\桌面\莫禧亮\华勤\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\华勤\上位机源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.cs
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.Designer.cs
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.AssemblyReference.cache
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.AxUdpClient.resources
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.GenerateResource.cache
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.CoreCompileInputs.cache
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_shuangtongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_sitongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.cs
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_sitongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.Designer.cs
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_sitongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_sitongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_sitongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.AssemblyReference.cache
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_sitongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.AxUdpClient.resources
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_sitongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.GenerateResource.cache
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_sitongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.CoreCompileInputs.cache
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_sitongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\28双通道\0731出差源码\LL-28_sitongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\耕德\LL-28_sitongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.cs
D:\桌面\莫禧亮\耕德\LL-28_sitongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.Designer.cs
D:\桌面\莫禧亮\耕德\LL-28_sitongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\耕德\LL-28_sitongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\耕德\LL-28_sitongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.AssemblyReference.cache
D:\桌面\莫禧亮\耕德\LL-28_sitongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.AxUdpClient.resources
D:\桌面\莫禧亮\耕德\LL-28_sitongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.GenerateResource.cache
D:\桌面\莫禧亮\耕德\LL-28_sitongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.CoreCompileInputs.cache
D:\桌面\莫禧亮\耕德\LL-28_sitongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\耕德\LL-28_sitongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\华勤\华贝LL-28\LL-28_sitongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\华勤\华贝LL-28\LL-28_sitongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.cs
D:\桌面\莫禧亮\华勤\华贝LL-28\LL-28_sitongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.Designer.cs
D:\桌面\莫禧亮\华勤\华贝LL-28\LL-28_sitongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\华勤\华贝LL-28\LL-28_sitongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.AssemblyReference.cache
D:\桌面\莫禧亮\华勤\华贝LL-28\LL-28_sitongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.AxUdpClient.resources
D:\桌面\莫禧亮\华勤\华贝LL-28\LL-28_sitongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.GenerateResource.cache
D:\桌面\莫禧亮\华勤\华贝LL-28\LL-28_sitongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.CoreCompileInputs.cache
D:\桌面\莫禧亮\华勤\华贝LL-28\LL-28_sitongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\华勤\华贝LL-28\LL-28_sitongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\LL-28\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\LL-28\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.cs
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\LL-28\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.Designer.cs
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\LL-28\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.AssemblyReference.cache
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\LL-28\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.AxUdpClient.resources
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\LL-28\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.GenerateResource.cache
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\LL-28\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.CoreCompileInputs.cache
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\LL-28\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\LL-28\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\LL-28\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.cs
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.Designer.cs
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.AssemblyReference.cache
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.AxUdpClient.resources
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.GenerateResource.cache
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.CoreCompileInputs.cache
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\华勤\华贝LL-28\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.cs
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.Designer.cs
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.AssemblyReference.cache
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.AxUdpClient.resources
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.GenerateResource.cache
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.CoreCompileInputs.cache
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.cs
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.Designer.cs
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.AssemblyReference.cache
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.AxUdpClient.resources
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.GenerateResource.cache
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.CoreCompileInputs.cache
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\单个\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.cs
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\单个\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.Designer.cs
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\单个\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\单个\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\单个\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.AssemblyReference.cache
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\单个\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.AxUdpClient.resources
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\单个\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.GenerateResource.cache
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\单个\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.CoreCompileInputs.cache
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\单个\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\华勤\华贝LL-28\正负压\单个\USB扫码枪版本\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\华贝\差压28\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.cs
D:\桌面\莫禧亮\华贝\差压28\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\TCP\ITcpClient.Designer.cs
D:\桌面\莫禧亮\华贝\差压28\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\华贝\差压28\huabei4tongdao\tongxin\NetWorkHelper\bin\Debug\NetWorkHelper.pdb
D:\桌面\莫禧亮\华贝\差压28\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.AssemblyReference.cache
D:\桌面\莫禧亮\华贝\差压28\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.AxUdpClient.resources
D:\桌面\莫禧亮\华贝\差压28\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.GenerateResource.cache
D:\桌面\莫禧亮\华贝\差压28\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.csproj.CoreCompileInputs.cache
D:\桌面\莫禧亮\华贝\差压28\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.dll
D:\桌面\莫禧亮\华贝\差压28\huabei4tongdao\tongxin\NetWorkHelper\obj\Debug\NetWorkHelper.pdb

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Office.Interop.Excel" version="15.0.4795.1001" targetFramework="net48" />
</packages>