创建命令实体类:Command
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EMNewsInfo
{
/// <summary>
/// 命令实体
/// </summary>
public class Command : ICloneable
{
public const string COPY = "copy";
public const string DELETE = "delete";
public const string RENAME = "rename";
/// <summary>
/// 命令编号
/// </summary>
public string Id
{
get;
set;
}
/// <summary>
/// 创建时间
/// </summary>
public DateTime CTime
{
get;
set;
}
/// <summary>
/// 本地路径
/// </summary>
public string LocalPath
{
get;
set;
}
/// <summary>
/// 本地Ip
/// </summary>
public string ServerIp
{
get;
set;
}
public int Port
{
get;
set;
}
public byte[] Data
{
get;
set;
}
/// <summary>
/// 服务器路径
/// </summary>
public string ServerPath
{
get;
set;
}
/// <summary>
/// 总字节数
/// </summary>
public long Count
{
get;
set;
}
/// <summary>
/// 命令类型
/// </summary>
public string Type
{
get;
set;
}
/// <summary>
/// 状态
/// 0.未处理
/// 1.已处理
/// </summary>
public int State
{
get;
set;
}
#region ICloneable 成员
public object Clone()
{
var t = new Command();
t.Count = this.Count;
t.CTime = this.CTime;
t.Id = this.Id;
t.LocalPath = this.LocalPath;
t.ServerIp = this.ServerIp;
t.ServerPath = this.ServerPath;
t.Type = this.Type;
return t;
}
#endregion
}
}
创建连接池相关类:ConnectionPool
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
namespace EMNewsInfo
{
public class ConnectionPool
{
private static System.Timers.Timer timer = new System.Timers.Timer();
static ConnectionPool()
{
timer.Interval = Keep_Alive * 1000;
timer.Elapsed += new System.Timers.ElapsedEventHandler(ClearOldCon);
timer.Start();
}
private static void ClearOldCon(object sender, EventArgs e)
{
lock (dicCon)
{
foreach (var key in dicCon.Keys)
{
var temp = dicCon[key];
for (int i = temp.Lst.Count - 1; i >= 0; i--)
{
var c = temp.Lst[i];
if (c.State == State.free && c.UpdateTime < DateTime.Now.AddSeconds(-Keep_Alive))
{
try
{
temp.Lst[i].CloseSocket();
}
catch
{
}
temp.Lst.RemoveAt(i);
}
}
}
}
}
private static int Keep_Alive = 30;
private static Dictionary<string, ConnectionCollection> dicCon = new Dictionary<string, ConnectionCollection>();
public static Dictionary<string, ConnectionCollection> DicCon
{
get
{
return dicCon;
}
}
private static Mutex m_mutex = new Mutex();
public static Connection GetConnection(string ip, int port)
{
try
{
m_mutex.WaitOne();
lock (dicCon)
{
string key = ip + "_" + port;
Connection con = null;
if (dicCon.ContainsKey(key))