首页 > 代码库 > socket多文件发送(压缩,解压)

socket多文件发送(压缩,解压)

1.客户端代码 
        public static void FileMoveInVirtualMachineForCompressor()
        {
            var obj = new object();
            string ip = "127.0.0.1";
            int port = 11000;
            List<string> files = Directory.GetFiles(@"C:\Users\admin\Desktop\sendFile").ToList();
            Dictionary<string, byte[]> infoList = new Dictionary<string, byte[]>();
            foreach (var file in files)
            {

                byte[] buffer = File.ReadAllBytes(file);

                infoList.Add(Path.GetFileName(file), buffer);
                
                
            }
           

            byte[] bs = Holworth.Utility.HraUtility.CompressionObject(infoList);
            string toPath = @"C:\Users\admin\Desktop\sendFile";
            string toFile = Path.Combine(toPath, DateTime.Now.ToString("yyyyMMdd")+ ".shape");
            //将数组写入文件 
            Stream writer = new FileStream(toFile, FileMode.Create, FileAccess.Write, FileShare.Write);
            writer.Write(bs, 0, bs.Length);
            writer.Flush();
            writer.Close();

            Net.SendFile(ip, port, toFile, 512, 900000);
        }
2.服务端监听
using SocketIM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FileListener
{
    class Program
    {
        static void Main(string[] args)
        {
            string ip = "127.0.0.1";
            int port = 11000;
            Net.ListenerAcceptFile(ip, port, @"d:\ReciveFoder");
            MessageBox.Show("监听程序已启动!!");
            Console.ReadKey();
        }
    }
}

3.Net.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SocketIM
{
    ////// Net : 提供静态方法,对常用的网络操作进行封装
    public class Net
    {
        public class ObjectState
        {
            public string fileName { get; set; }
            public Socket workSocket { get; set; }
            public Thread workThread { get; set; }
        }
        private Net()
        {
        }


        ////// 向远程主机发送数据
        //////要发送数据且已经连接到远程主机的 Socket///待发送的数据///发送数据的超时时间,以秒为单位,可以精确到微秒///0:发送数据成功;-1:超时;-2:发送数据出现错误;-3:发送数据时出现异常////// 当 outTime 指定为-1时,将一直等待直到有数据需要发送
        public static int SendData(Socket socket, byte[] buffer, int outTime)
        {
            if (socket == null || socket.Connected == false)
            {
                throw new ArgumentException("参数socket 为null,或者未连接到远程计算机");
            }
            if (buffer == null || buffer.Length == 0)
            {
                throw new ArgumentException("参数buffer 为null ,或者长度为 0");
            }

            int flag = 0;
            try
            {
                int totalLen = buffer.Length;
                int sndLen = 0;

                while (true)
                {
                    if ((socket.Poll(outTime * 100, SelectMode.SelectWrite) == true))
                    {        // 收集了足够多的传出数据后开始发送
                        sndLen = socket.Send(buffer, sndLen, totalLen, SocketFlags.None);
                        totalLen -= sndLen;
                        if (totalLen == 0)
                        {                                        // 数据已经全部发送
                            flag = 0;
                            break;
                        }
                        else
                        {
                            if (sndLen > 0)
                            {                                    // 数据部分已经被发送continue;
                            }
                            else
                            {                                                // 发送数据发生错误
                                flag = -2;
                                break;
                            }
                        }
                    }
                    else
                    {                                                        // 超时退出
                        flag = -1;
                        break;
                    }
                }
            }
            catch (SocketException e)
            {

                flag = -3;
            }
            return flag;
        }


        ////// 向远程主机发送文件
        //////要发送数据且已经连接到远程主机的 socket///待发送的文件名称///文件发送时的缓冲区大小///发送缓冲区中的数据的超时时间///0:发送文件成功;-1:超时;-2:发送文件出现错误;-3:发送文件出现异常;-4:读取待发送文件发生错误////// 当 outTime 指定为-1时,将一直等待直到有数据需要发送
        public static int SendFile(string ip, int port, string fileName, int maxBufferLength, int outTime)
        {
            IPAddress address = IPAddress.Parse(ip);
            IPEndPoint endpoint = new IPEndPoint(address, port);
            //创建服务端负责监听的套接字,参数(使用IPV4协议,使用流式连接,使用TCO协议传输数据)
            Thread.Sleep(1500);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(endpoint);
            if (socket.Connected)
            {
                Console.WriteLine(socket.RemoteEndPoint + "连接成功");
            }
            if (fileName == null || maxBufferLength <= 0)
            {
                throw new ArgumentException("待发送的文件名称为空或发送缓冲区的大小设置不正确.");
            }
            int flag = 0;
            try
            {
                var fileBytes = Encoding.UTF8.GetBytes(fileName);
                var fbs = new byte[100];
                for (int i = 0; i < fileBytes.Length; i++)
                {
                    fbs[i] = fileBytes[i];
                }
                socket.Send(fbs);

                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                long fileLen = fs.Length;                        // 文件长度
                long totalLen = fileLen;                            // 未读取部分
                int readLen = 0;                                // 已读取部分
                byte[] buffer = null;

                if (fileLen <= maxBufferLength)
                {            /* 文件可以一次读取*/
                    buffer = new byte[fileLen];
                    readLen = fs.Read(buffer, 0, (int)fileLen);
                    flag = SendData(socket, buffer, outTime);
                }
                else
                {
                    /* 循环读取文件,并发送 */
                    while (totalLen != 0)
                    {
                        if (totalLen < maxBufferLength)
                        {
                            buffer = new byte[totalLen];
                            readLen = fs.Read(buffer, 0, Convert.ToInt32(totalLen));
                        }
                        else
                        {
                            buffer = new byte[maxBufferLength];
                            readLen = fs.Read(buffer, 0, maxBufferLength);
                        }
                        if ((flag = SendData(socket, buffer, outTime)) < 0)
                        {
                            break;
                        }
                        totalLen -= readLen;
                    }
                }
                fs.Flush();
                fs.Close();
                File.Delete(fileName);
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
            }
            catch (IOException e)
            {

                flag = -4;
            }
            if (flag == 0)
            {
                Console.WriteLine(fileName + "文件发送成功");
                socket.Close();
                Console.WriteLine("连接关闭");
            }
            else
            {
                Console.WriteLine(fileName + "文件发送失败,i=" + flag);
            }
            return flag;
        }
        private static void WatchConnecting(object info)
        {
            ObjectState state = (ObjectState)info;
            Socket socketWatch = state.workSocket;
            while (true)//持续不断的监听客户端的请求            
            {
                //开始监听 客户端连接请求,注意:Accept方法,会阻断当前的线程
                Socket connection = socketWatch.Accept();


                if (connection.Connected)
                {

                    //创建通信线程
                    Thread thradRecMsg = new Thread(RecMsg);
                    state.workSocket = connection;
                    state.workThread = thradRecMsg;
                    thradRecMsg.IsBackground = true;
                    thradRecMsg.Start(state);

                }
            }

        }
        ////// 接收消息
        private static void RecMsg(object socketClientPara)
        {
            string ext = string.Empty;
            string fileSourcePath = string.Empty;
            ObjectState state = (ObjectState)socketClientPara;
            string fileName = state.fileName;//获得用户保存文件的路径
            Socket socketClient = state.workSocket;
            FileStream fs = null;
            while (true)
            {
                //定义一个接受用的缓存区(100M字节数组)
                //将接收到的数据存入arrMsgRec数组,并返回真正接受到的数据的长度   
                if (socketClient.Connected)
                {
                    try
                    {

                        byte[] fileBuffer = new byte[100];
                        int size1= socketClient.Receive(fileBuffer);

                        fileSourcePath = Encoding.UTF8.GetString(fileBuffer).Trim();
                        var chs = fileSourcePath.ToCharArray();
                        var chList = new List<char>();
                        foreach (var item in chs)
                        {
                            if (item != \0)
                            {
                                chList.Add(item);
                            }

                        }
                        fileSourcePath = string.Join("", chList);
                        fileName = Path.Combine(state.fileName, Path.GetFileName(fileSourcePath));
                        ext = Path.GetExtension(fileName);
                        //因为终端每次发送文件的最大缓冲区是512字节,所以每次接收也是定义为512字节
                        byte[] buffer = new byte[512];
                        int size = 0;
                        //统计实际文件大小
                        long len = 0;
                        //创建文件流,然后让文件流来根据路径创建一个文件
                        fs = new FileStream(fileName, FileMode.Append);
                        DateTime oTimeBegin = DateTime.Now;
                        //从终端不停的接受数据,然后写入文件里面,只到接受到的数据为0为止,则中断连接
                        while ((size = socketClient.Receive(buffer, 0, buffer.Length, SocketFlags.None)) > 0)
                        {
                            fs.Write(buffer, 0, size);
                            len += size;
                        }
                        DateTime oTimeEnd = DateTime.Now;
                        TimeSpan oTime = oTimeEnd.Subtract(oTimeBegin);
                        fs.Flush();
                        fs.Dispose();
                        //解压文件.DEFP;

                        var obj=(Dictionary<string,byte[]>) Holworth.Utility.HraUtility.DeSerializerFileToObj(fileName);

                        foreach (var item in obj)
                        {
                            string path = Path.Combine(state.fileName, item.Key);
                            FileStream fw= new FileStream(path, FileMode.Append);
                            fw.Write(item.Value, 0, item.Value.Length);
                            fw.Flush();
                            fw.Dispose();
                        }
                        File.Delete(fileName);
                        Console.WriteLine("文件保存成功:" + fileName);
                        Console.WriteLine("接收文件用时:" + oTime.ToString() + ",文件大小:" + len / 1024 + "kb");
                    }
                    catch (Exception ex)
                    {
                        if (fs != null)
                        {
                            fs.Dispose();
                        }
                        
                        Console.WriteLine(socketClient.RemoteEndPoint + "下线了");

                        break;
                    }
                    finally
                    {
                        socketClient.Shutdown(SocketShutdown.Both);
                        socketClient.Close();
                    }
                }
                else
                {

                }
            }
        }

   

        /// <summary>
        /// 监听并接收文件
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="fileName"></param>
        public static void ListenerAcceptFile(string ip, int port, string fileName)
        {
            //创建服务端负责监听的套接字,参数(使用IPV4协议,使用流式连接,使用Tcp协议传输数据)
            Socket socketListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socketListen.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            //获取Ip地址对象
            IPAddress address = IPAddress.Parse(ip);
            //创建包含Ip和port的网络节点对象
            IPEndPoint endpoint = new IPEndPoint(address, port);

            //将负责监听的套接字绑定到唯一的Ip和端口上          
            socketListen.Bind(endpoint);
            //设置监听队列的长度
            socketListen.Listen(10);
            connectDone.Set();
            ObjectState state = new ObjectState();

            //创建负责监听的线程,并传入监听方法
            Thread threadWatch = new Thread(WatchConnecting);
            state.fileName = fileName;
            state.workSocket = socketListen;
            state.workThread = threadWatch;
            threadWatch.IsBackground = true;//设置为后台线程
            threadWatch.Start(state);//开始线程

        }
        public static void CloseTcpSocket(Thread threadWatch, Socket socketWatch)
        {

            threadWatch.Abort();
            socketWatch.Close();
            Console.WriteLine("服务器关闭监听");
        }
        public static ManualResetEvent connectDone = new ManualResetEvent(false);
        public static void FileMove(string ip, int port, string fromPath, string toPath)
        {

            int i = SendFile(ip, port, fromPath, 512, 90000);
            Console.WriteLine("文件从" + fromPath + "" + toPath + "移动成功!!!!");
        }



    }
}

3.Utility工具类,慢看吧,里面有这次的压缩代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using a = Utility;
using System.Net;
using System.IO;
using System.Data;
using System.Data.OleDb;
using ut = Utility;
using System.Collections;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;
using Framework;
using Oracle.DataAccess.Client;
using System.Runtime.Remoting.Messaging;
using Contract.Domain;
using System.Reflection;
using System.Collections.Concurrent;
using Framework.Domain;

namespace Holworth.Utility
{
    public class DataBaseInfo
    {
        public string datasource { get; set; }
        public string user { get; set; }
        public string datasource2 { get; set; }
        public string password { get; set; }
        public string database { get; set; }
        public string port { get; set; }
        public string dbSwitch { get; set; }
    }
    public class HraUtility
    {
        public enum AppEnum
        {
            //web应用的配置文件
            Web=0,
            //非web应用的配置文件
            App=1,
        }
        private static object lockDataBaseInfo = new object();
        private static DataBaseInfo _dbWebInfo = null;
        private static DataBaseInfo _dbAppInfo = null;
        public static DataBaseInfo GetDataBaseInfo(AppEnum app)
        {
            DataBaseInfo info = null;
            if (app == AppEnum.Web)
            {
                info = _dbWebInfo;
            }
            else if (app ==AppEnum.App)
            {
                info = _dbAppInfo;
            }

            if (info == null)
            {
                lock (lockDataBaseInfo)
                {
                    if (info == null)
                    {
                        if (app == AppEnum.Web)
                        {
                            info = _dbWebInfo=new DataBaseInfo();
                        }
                        else if (app == AppEnum.App)
                        {
                            info = _dbAppInfo=new DataBaseInfo();
                        }
                        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
                        xmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory +app.ToString()+".config");
                        System.Xml.XmlNodeList nodes = xmlDoc.SelectNodes("/configuration/databaseSettings/add");
                        var ps = info.GetType().GetProperties().ToList().ToDictionary(x => x.Name);
                        foreach (System.Xml.XmlNode node in nodes)
                        {
                            string key = node.Attributes["key"].InnerText;
                            string value = http://www.mamicode.com/node.Attributes["value"].Value;
                            string realKey = key.Split(.)[key.Split(.).Length - 1];//我实际的标记是db.key如db.database ,db.user,db.password
                            if (realKey == "user")
                            {
                                value = value.ToUpper();
                            }
                            ps[realKey].SetValue(info, value);
                        }
                    }
                }
            }
            return info;
        }



        /// <summary>
        /// xml Sql操作接口
        /// </summary>

        public static EntityRowMapper EntityRowMapper = new EntityRowMapper();
        public static CSVHelper csvHelper = new CSVHelper();
        public static IList<T> ListToT<T>(System.Collections.IList list)
        {

            System.Collections.Generic.IList<T> returnList = new System.Collections.Generic.List<T>();
            foreach (T a in list)
            {
                returnList.Add(a);
            }
            return returnList;
        }

        public static void DownLoad(string url, string fileName)
        {
            bool flag = false;
            //打开上次下载的文件
            long SPosition = 0;
            //实例化流对象
            FileStream FStream;
            string strFileName = fileName;
            //判断要下载的文件夹是否存在
            if (File.Exists(strFileName))
            {
                File.Delete(strFileName);
                ////打开要下载的文件
                //FStream = File.OpenWrite(strFileName);
                ////获取已经下载的长度
                //SPosition = FStream.Length;
                //FStream.Seek(SPosition, SeekOrigin.Current);
            }
            FStream = new FileStream(strFileName, FileMode.Create);
            SPosition = 0;
            HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);
            if (SPosition > 0)
                myRequest.AddRange((int)SPosition);             //设置Range值
            Stream myStream = myRequest.GetResponse().GetResponseStream();
            //定义一个字节数据
            byte[] btContent = new byte[512];
            int intSize = 0;
            intSize = myStream.Read(btContent, 0, 512);
            while (intSize > 0)
            {
                FStream.Write(btContent, 0, intSize);
                intSize = myStream.Read(btContent, 0, 512);
            }
            //关闭流
            FStream.Close();
            myStream.Close();
        }
        public static decimal ChangeCross(string from, string to, int twice)
        {
            string url = a.ConfigManager.GetConfig("CrossUrl");
            url += string.Format("?s={0}=X&f=l1", from.ToUpper(), to.ToUpper());
            System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); //从URL地址得到一个WEB请求    
            System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); //从WEB请求得到
            if (myrp.StatusCode == HttpStatusCode.OK)
            {
                long totalBytes = myrp.ContentLength; //从WEB响应得到总字节数    
                System.IO.Stream st = myrp.GetResponseStream(); //从WEB请求创建流(读
                StreamReader responseReader = new StreamReader(st);
                string s = responseReader.ReadToEnd();
                if (!string.IsNullOrEmpty(s))
                {
                    return decimal.Parse(s);
                }
                else
                {
                    throw new Exception("无法获取相应汇率");
                }
            }

            return 0;
        }
        /// <summary>
        /// 获取Excel 数据
        /// </summary>
        /// <param name="strPath"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public static DataTable GetExcelSheetContent(string strPath, string sheetName)
        {

            string mystring = "";
            DataTable dt = new DataTable();
            mystring = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = ‘" + strPath + "‘;Extended Properties=‘Excel 8.0;HDR=NO;IMEX=1;‘";
            if (System.IO.Path.GetExtension(strPath).ToLower().EndsWith("xlsx"))
            {
                mystring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strPath + ";Extended Properties=‘Excel 12.0;HDR=YES‘";
            }
            OleDbConnection connection = new OleDbConnection(mystring);
            OleDbDataAdapter da = null;
            try
            {

                da = new OleDbDataAdapter("select * from [" + sheetName + "]", connection);
                da.Fill(dt);
                return dt;
            }
            catch (OleDbException err)
            {
                throw new Exception("执行查询语句时出错:" + err.Message);
            }
            finally
            {
                connection.Close();
                da.Dispose();
            }
        }
        /// <summary>
        /// 获取Excel 表格名
        /// </summary>
        /// <param name="strPath"></param>
        /// <returns></returns>
        public static string[] GetExcelTableName(string strPath)
        {

            string mystring = "";
            mystring = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = ‘" + strPath + "‘;Extended Properties=‘Excel 8.0;HDR=YES;IMEX=1;‘";
            if (System.IO.Path.GetExtension(strPath).ToLower().EndsWith("xlsx"))
            {
                mystring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strPath + ";Extended Properties=‘Excel 12.0;HDR=YES‘";
            }
            //IList<string> tblNames = null;
            DataTable tblSchema = null;
            string tableName = "";
            OleDbConnection connection = new OleDbConnection(mystring);
            try
            {
                if (connection.State != ConnectionState.Open)
                    connection.Open();
                //Prepare the command
                tblSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                string[] mySheetName = new string[tblSchema.Rows.Count];
                int i = 0;
                foreach (DataRow row in tblSchema.Rows)
                {
                    tableName = row["TABLE_NAME"].ToString();
                    mySheetName[i] = tableName;
                    i++;
                }
                return mySheetName;
            }
            catch (OleDbException err)
            {
                if (err.ErrorCode == -2147467259)
                    throw new Exception("您选择的Excel文件不是预期的格式!");
                else
                    throw new Exception("执行查询语句时出错:" + err.Message);
            }
            finally
            {
                connection.Close();
            }
            
        }
        /// <summary>
        /// 将“abc_d_ef”类型的字符串转换成首字母大写的"AbcDEf"
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string NameFormatter(string name)
        {
            string[] s = name.Split(_);
            for (int i = 0; i < s.Count(); i++)
            {
                s[i] = s[i].Substring(0, 1).ToUpper() + s[i].Substring(1).ToLower();
            }
            name = string.Concat(s);
            return name;
        }
        /// <summary>
        /// 将AbcDef转成ABC_DEF
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string NameConverter(string name)
        {
            List<char> c = name.ToList();
            int count = c.Count;
            for (int i = 1; i < count; i++)
            {
                if (c[i] >= A && c[i] <= Z)
                {
                    c.Insert(i, _);
                    i++;
                }
            }
            string result = string.Concat(c);
            return result;
        }
        /// <summary>
        /// 全角转半角
        /// </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);
        }
        private static Framework.IService.ICommonService GetDao()
        {
            Spring.Context.IApplicationContext ctx = Spring.Context.Support.ContextRegistry.GetContext();
            return (Framework.IService.ICommonService)ctx["CommonService"];
        }
        public static string ConvertToEntityColumnName(string name)
        {

            List<string> strList = name.Split(_).ToList();
            StringBuilder sb = new StringBuilder();
            foreach (string s2 in strList)
            {
                sb.Append(ReplaceString(s2));
            }
            return sb.ToString();
        }

        public static string ReplaceString(string s)
        {
            return Regex.Replace(s, (string)@"([A-Za-z]{1})([A-Za-z]*)", (MatchEvaluator)MatchEval);


        }
        public static string ConvertToTableColumnName(string name)
        {
            name = Regex.Replace(name, @"([A-Z]{1})([a-z]*)", MatchEval2);
            name = name.TrimEnd(_);
            return name;
        }
        private static string MatchEval2(Match match)
        {
            return match.Groups[1].Value.ToUpper() + match.Groups[2].Value.ToUpper() + "_";
        }
        private static string MatchEval(Match match)
        {
            return match.Groups[1].Value.ToUpper() + match.Groups[2].Value.ToLower();
        }

        public static Dictionary<string, string> ChangeType(string NodeSource, string DataValueField, string DataTextField, object cellValue)
        {

            var Dao = GetDao();
            Framework.QueryInfo NodeSourceInfo = new Framework.QueryInfo();
            NodeSourceInfo.CustomSQL = "select " + DataValueField + "," + DataTextField + " from " + NodeSource;
            Dictionary<string, string> NodeSourceDictionary = new Dictionary<string, string>();
            IList NodeSourceList = Dao.FindList(NodeSourceInfo);
            foreach (dynamic item in NodeSourceList)
            {
                object[] objs = item as object[];
                NodeSourceDictionary.Add(objs[0].ToString(), objs[1].ToString());

            }
            return NodeSourceDictionary;
        }

        public  static byte[] CompressionObject(object DataOriginal)
        {
            if (DataOriginal == null) return null;
            BinaryFormatter bFormatter = new BinaryFormatter();
            MemoryStream mStream = new MemoryStream();
            bFormatter.Serialize(mStream, DataOriginal);
            byte[] bytes = mStream.ToArray();
            MemoryStream oStream = new MemoryStream();
            DeflateStream zipStream = new DeflateStream(oStream, CompressionMode.Compress);
            zipStream.Write(bytes, 0, bytes.Length);
            zipStream.Flush();
            zipStream.Close();
            return oStream.ToArray();
        }
        public static object DecompressionObject(byte[] bytes)
        {
            if (bytes == null) return null;
            MemoryStream mStream = new MemoryStream(bytes);
            mStream.Seek(0, SeekOrigin.Begin);
            DeflateStream unZipStream = new DeflateStream(mStream, CompressionMode.Decompress, true);
            object dsResult = null;
            BinaryFormatter bFormatter = new BinaryFormatter();
            dsResult = (object)bFormatter.Deserialize(unZipStream);
            return dsResult;
        }
        /// <summary> 
        /// 序列化对象,将对象写入文件,然后还原. 
        /// </summary> 
        public static void SerializerObjToFile(string serializerFileName, object obj)
        {

            byte[] bs = CompressionObject(obj);

            string path = HraUtility.EntityRowMapper.GetFilePath("admin/InitDataBase/Sql/SerializerFile/" + serializerFileName + ".shape");
            //将数组写入文件 
            Stream writer = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write);
            writer.Write(bs, 0, bs.Length);
            writer.Flush();
            writer.Close();



        }
        public static object DeSerializerFileToObj(string relativePath)
        {
            //"admin/InitDataBase/Sql/SerializerFile/" + serializerFileName + ".shape"
            string path = relativePath;// HraUtility.EntityRowMapper.GetFilePath(relativePath);
            //读取文件,先写入数组,再从数组转换为对象.Easy! 
            FileStream fs = File.Open(path, FileMode.OpenOrCreate,FileAccess.ReadWrite);
            byte[] bss = new byte[fs.Length];
            int i = fs.Read(bss, 0, (int)fs.Length);
            fs.Dispose();
            object o = DecompressionObject(bss); //还原,ok 
            return o;
        }
        public static object lockListObj = new object();
        public static object lockSequence = new object();
        public static object lockGetSequence = new object();
        public static object lockDeleteSequence = new object();
        public static object lockReBuildSequence = new object();
        /// <summary>
        /// BulkCopy
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="targetTable"></param>
        /// <param name="IdField"></param>
        /// <param name="NeedId"></param>
        public static void DataTableWriteToServer(DataTable dt, string targetTable, string IdField = "ID", bool NeedId = false,string v_seq= "BULKCOPYSEQUENCE")
        {
            var Dao = GetDao();
            QueryInfo info = new QueryInfo();
            DataTable table = null;
            Int64 increId = 0;
            lock (lockSequence)
            {

                if (NeedId)
                {
                    #region 1.获取当前序列之
                    QueryInfo searchInfo = new QueryInfo();
                    searchInfo.CustomSQL = $"select {v_seq}.NEXTVAL from dual";
                    table = Dao.ExecuteDataSet(searchInfo).Tables[0];
                    increId = Convert.ToInt64(table.Rows[0][0].ToString());
                    #endregion



                    #region 2.改变步长
                    info.NamedQuery = "PRO_SEQUENCE";
                    info.Parameters.Add("v_simulation_number", dt.Rows.Count-1);
                    info.Parameters.Add("v_seq", v_seq);
                    Dao.ExecuteNonQuery(info);
                    #endregion


                    #region 3.改变序列的新值
                    searchInfo = new QueryInfo();
                    searchInfo.CustomSQL = $"select {v_seq}.NEXTVAL from dual";
                    table = Dao.ExecuteDataSet(searchInfo).Tables[0];
                    #endregion


                    #region 4.步长改为1
                    info = new QueryInfo();
                    info.NamedQuery = "PRO_SEQUENCE";
                    info.Parameters.Add("v_simulation_number", -1);
                    info.Parameters.Add("v_seq", v_seq);
                    Dao.ExecuteNonQuery(info); 
                    #endregion


                    increId = Convert.ToInt64(table.Rows[0][0].ToString());
                    foreach (DataRow t in dt.Rows)
                    {
                        t[IdField] = increId++;

                    }
                }
               
                //System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                OracleConnection conn =(OracleConnection) Dao.GetSession().Connection;
                    //new OracleConnection(connOrcleString);
                OracleBulkCopy bulkCopy = new OracleBulkCopy(conn,
                    OracleBulkCopyOptions.UseInternalTransaction);
                bulkCopy.BulkCopyTimeout = 260 * 1000;
                bulkCopy.DestinationTableName = targetTable; //服务器上目标表的名称
                bulkCopy.BatchSize = 5000; //每一批次中的行数
                try
                {
                    IDataReader rd = new DataTableReader(dt);
                    //conn.Open();
                    if (dt != null && dt.Rows.Count != 0)
                        
                        bulkCopy.WriteToServer(rd); //将提供的数据源中的所有行复制到目标表中
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    info = new QueryInfo();
                    info.NamedQuery = "PRO_SEQUENCE";
                    info.Parameters.Add("v_simulation_number", -1);
                    info.Parameters.Add("v_seq", v_seq);
                    Dao.ExecuteNonQuery(info);
                    conn.Close();
                    if (bulkCopy != null)
                        bulkCopy.Close();

                }
            }

        }
        /// <summary>
        /// 获取Hibernate对象映射的序列
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>

        public static string GetSequenceName<T>() where T : Framework.Domain.Entity, new()
        {
            var ctx = Spring.Context.Support.ContextRegistry.GetContext();
            var mapping = ((Spring.Data.NHibernate.LocalSessionFactoryObject)ctx.GetObject("&SessionFactory")).Configuration.GetClassMapping(typeof(T));
            if (((((NHibernate.Mapping.SimpleValue)mapping.Table.IdentifierValue)).IdentifierGeneratorStrategy) != "native")
            {
                return "HIBERNATE_SEQUENCE";
            }
            var sequece = ((NHibernate.Mapping.SimpleValue)mapping.Table.IdentifierValue).IdentifierGeneratorProperties["sequence"].ToUpper();
            return sequece;
        }
        /// <summary>
        /// List<T>最终使用Bulkcopy的方式实现数据的高效插入,如果可以提供MapDataRow请尽量提供,尽量避免反射带来的效率问题,虽然内部已经使用了高效反射,但任不及直接赋值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="DataList"></param>
        /// <param name="MapDataRow">将对象T转换为DataRow</param>

        public static void DataListWriteToServer<T>(IEnumerable<T> DataList) where T : Framework.Domain.Entity,new()
        {
            ConcurrentDictionary<DataRow, Framework.Domain.Entity> dr2obj = new ConcurrentDictionary<DataRow, Framework.Domain.Entity>();
            if (DataList.Count() <= 0)
            {
                return;
            }
            bool IsMapDataRow = DataList.FirstOrDefault() is IMapRow<T>;
            string typeName = typeof(T).FullName;
            var ctx = Spring.Context.Support.ContextRegistry.GetContext();
            var mapping = ((Spring.Data.NHibernate.LocalSessionFactoryObject)ctx.GetObject("&SessionFactory")).Configuration.GetClassMapping(typeof(T));
            var tableName = mapping.Table.Name;
            DataTable targetTable = GetDao().ExecuteDataSet(new QueryInfo() { CustomSQL = $"select * from {tableName} where 1!=1" }).Tables[0];
            Hashtable columnsType = new Hashtable();
            foreach (DataColumn col in targetTable.Columns)
            {
                columnsType.Add(col.ColumnName, col.DataType.Name);
            }
            var pmap = mapping.PropertyIterator;
            //查找主键
            string primaryKey = ((NHibernate.Mapping.Column)(mapping.Key.ColumnIterator.FirstOrDefault())).Name;
            //映射列和字段信息的PropertyColumnMappingInfo的集合
            Hashtable pcMappinght = new Hashtable();
            lock (lockListObj)
            {
                foreach (NHibernate.Mapping.Property item in pmap)
                {
                    //面相对象里Bag在数据中不体现
                    //if (item.ColumnIterator.GetType().Name == "ISelectable[]")
                    //{
                    //    continue;
                    //}

                    NHibernate.Mapping.Column c = (NHibernate.Mapping.Column)item.ColumnIterator.FirstOrDefault();


                    ////等下再改
                    Type columnType = null;
                    //1对多的属性如children没有对应的列
                    if (c != null)
                    {
                        string columnTypeName = columnsType[c.Name].ToString();
                        switch (columnTypeName)
                        {
                            case "String":
                                columnType = typeof(string);
                                break;
                            case "Int16":
                            case "Int32":
                            case "Int64":
                                columnType = typeof(int);
                                break;
                            case "Decimal":
                                columnType = typeof(decimal);
                                break;
                            case "DateTime":
                                columnType = typeof(DateTime);
                                break;
                            case "Boolean":
                            case "bool":
                                columnType = typeof(bool);
                                break;
                            default:
                                break;
                        }

                        //targetTable.Columns.Add(c.Name, columnType);
                        if (!pcMappinght.ContainsKey(c.Name + "," + item.Name))
                        {
                            PropertyColumnMappingInfo map = new PropertyColumnMappingInfo();
                            map.ColumnName = c.Name;
                            map.PropertyName = item.Name;
                            map.ColumnType = columnType;
                            var key = c.Name + "," + item.Name;
                            pcMappinght.Add(key, map);
                        }
                    }
                }
                IMapRow<T> mapRow = null;
                foreach (var item in DataList)
                {
                    DataRow dtRow = targetTable.NewRow();
                    if (IsMapDataRow)
                    {
                        mapRow = (IMapRow<T>)item;
                        dtRow = mapRow.MapDataRow(dtRow);
                    }
                    else
                    {
                        foreach (NHibernate.Mapping.Property p in pmap)
                        {

                            object curValue = http://www.mamicode.com/item.FastGetValue(typeName, p.Name);
                            if (p.IsEntityRelation == true)
                            {
                                if (curValue != null)
                                    curValue = ((Framework.Domain.Entity)curValue).Id;
                            }
                            //面相对象里Bag在数据中不体现
                            if (p.ColumnIterator.GetType().Name == "ISelectable[]")
                            {
                                continue;
                            }
                            NHibernate.Mapping.Column c = (NHibernate.Mapping.Column)p.ColumnIterator.FirstOrDefault();
                            var key = c.Name + "," + p.Name;
                            var map = (PropertyColumnMappingInfo)pcMappinght[key];
                            if (curValue =http://www.mamicode.com/= null && c.IsNullable == false)
                            {
                                if (map.ColumnType == typeof(int) || map.ColumnType == typeof(Int16) || map.ColumnType == typeof(long))
                                {
                                    curValue = default(int);
                                }
                                if (map.ColumnType == typeof(DateTime))
                                {
                                    curValue = default(DateTime).Date;
                                }
                                if (map.ColumnType == typeof(decimal))
                                {
                                    curValue = default(decimal);
                                }
                                if (map.ColumnType == typeof(string))
                                {
                                    curValue = default(string);
                                }
                                if (map.ColumnType == typeof(bool))
                                {
                                    curValue = default(bool);
                                }
                            }
                            if (curValue != null)
                            {
                                dtRow[c.Name] = Convert.ChangeType(curValue, map.ColumnType);
                            }
                            else
                            {
                                dtRow[c.Name] = DBNull.Value;
                            }
                        }
                    }
                    targetTable.Rows.Add(dtRow);
                    dr2obj.TryAdd(dtRow, item);
                    
                }

               
                if (((((NHibernate.Mapping.SimpleValue)mapping.Table.IdentifierValue)).IdentifierGeneratorStrategy)!="native")
                {
                    var sequece = ((NHibernate.Mapping.SimpleValue)mapping.Table.IdentifierValue).IdentifierGeneratorProperties["sequence"].ToUpper();
                    //bulkcopy
                    DataTableWriteToServer(targetTable, tableName.ToUpper(), primaryKey, true,sequece);
                }
                else
                {
                    DataTableWriteToServer(targetTable, tableName.ToUpper(), primaryKey, true, "HIBERNATE_SEQUENCE");

                }
                foreach (DataRow dr in targetTable.Rows)
                {
                    dr2obj[dr].Id = dr[primaryKey].ToString();
                }
            }

        }
        public static void InitColumns(Array arr, ref Dictionary<string, DataColumn> dicCols, ref DataTable table)
        {

            for (int i = 0; i < arr.Length; i++)
            {

                if ((arr as dynamic)[i] is Array)
                {

                    InitColumns((arr as dynamic)[i], ref dicCols, ref table);

                }
                else
                {


                    if (arr.Length >= dicCols.Keys.Count)
                    {
                        dicCols.Clear();
                        for (int ii = 0; ii < arr.Length; ii++)
                        {

                            string colName = Guid.NewGuid().ToString();
                            DataColumn col = new DataColumn(colName);
                            if (!dicCols.ContainsKey(colName))
                            {
                                dicCols.Add(colName, col);

                            }


                        }





                    }


                }

            }



        }

        public static DataTable ArrayConvert2DataTable(Array arr)
        {
            DataTable tmpT = new DataTable();
            Dictionary<string, DataColumn> dicCols = new Dictionary<string, DataColumn>();
            Dictionary<string, DataRow> dicRows = new Dictionary<string, DataRow>();
            //J=交 C=错
            bool isJC = !(arr.GetType().Name.Contains(,));
            //交错数组处理
            if (isJC)
            {
                //交错数组第一个维度的元素个

                DataTable table = new DataTable();
                List<int> dims = new List<int>();
                InitColumns(arr, ref dicCols, ref table);
                foreach (var item in dicCols)
                {
                    table.Columns.Add(item.Value);
                }
                int currRowIndex = 0;
                SearchTable(ref currRowIndex, arr, arr, ref table);

                return table;

            }
            //多维数组处理
            else
            {

                int rank = arr.Rank;
                int cols = arr.GetLength(rank - 1);

                for (int i = 0; i < cols; i++)
                {
                    DataColumn col = new DataColumn(Guid.NewGuid().ToString());
                    tmpT.Columns.Add(col);
                }

                Dictionary<int, int> dims = new Dictionary<int, int>();
                int currRowIndex = -1;
                Dictionary<int, DataRow> dicRow = new Dictionary<int, DataRow>();
                var iterator = arr.GetEnumerator();
                int count = 0;
                while (iterator.MoveNext())
                {
                    var curr = iterator.Current;
                    if (count % cols == 0)
                    {
                        currRowIndex++;
                        DataRow dr = tmpT.NewRow();
                        tmpT.Rows.Add(dr);
                        dicRow.Add(currRowIndex, dr);
                        dr[0] = curr.ToString();
                        if (count == cols)
                        {
                            count = 0;
                        }

                    }
                    else
                    {
                        tmpT.Rows[currRowIndex][count] = curr.ToString();


                    }
                    count++;


                }










            }
            return tmpT;
        }

        private static void SearchTable(ref int currRowIndex, Array ori, Array curr, ref DataTable table)
        {

            for (int i = 0; i < curr.Length; i++)
            {
                bool isa = (curr as dynamic)[i] is Array;
                if (isa)
                {

                    SearchTable(ref currRowIndex, ori, (curr as dynamic)[i], ref table);

                }
                else
                {
                    if (table.Rows.Count < currRowIndex + 1)
                    {
                        DataRow newRow = table.NewRow();
                        table.Rows.Add(newRow);
                    }

                    try
                    {
                        table.Rows[currRowIndex][i] = (curr as Array).GetValue(i);
                    }
                    catch (Exception)
                    {

                        ;
                    }
                    if (i == curr.Length - 1)
                        currRowIndex++;

                }

            }







        }
        private Spring.Caching.ICache cache;
        private Spring.Caching.ICache SpringCache
        {
            get
            {
                if (cache == null)
                    cache = (Spring.Caching.ICache)ctx.GetObject("AspNetCache");
                return cache;
            }
            set { cache = value; }
        }
        private static Spring.Caching.ICache getCache()
        {
            var cache = (Spring.Caching.ICache)Spring.Context.Support.ContextRegistry.GetContext().GetObject("AspNetCache");
            return cache;
        }
        private Spring.Context.IApplicationContext _ctx;
        protected Spring.Context.IApplicationContext ctx
        {
            get
            {
                if (_ctx == null)
                    _ctx = Spring.Context.Support.ContextRegistry.GetContext();
                return _ctx;
            }
        }

     

        public static string ConvertValue2Name(string IdValue, string entity = "SysEnumDict", string idField = "EnumValue", string textField = "EnumName")
        {
            var ha = CallContext.GetData("Current") as Hashtable;
            if (ha == null)
            {
                ha = new Hashtable();
                CallContext.SetData("Current", new Hashtable());
            }
            Dictionary<string, string> dic = null;
            if (!ha.ContainsKey(entity + idField + textField))
            {
                dic = ChangeType(entity, idField, textField, "");
                ha[entity + idField + textField] = dic;
            }
            else
            {
                dic = ha[entity + idField + textField] as Dictionary<string, string>;

            }
            var value = http://www.mamicode.com/"";
            if (dic.ContainsKey(IdValue))
            {
                value = dic[IdValue];
            }

            return value;
        }
        /// <summary>
        /// 通用生成具有上下级树的结构代码
        /// </summary>
        /// <param name="valueField">主键id</param>
        /// <param name="entity">表名</param>
        /// <param name="parentKey">parent_id</param>
        /// <param name="textField">文本字段</param>
        /// <param name="isFirst">是否第一次</param>
        /// <param name="where">条件</param>
        /// <returns></returns>
        public static IList<EasyUiTree> LoadEntityTree(string valueField, string entity,string nodeSourceKey, string parentKey, string textField, string where = "", string levelField="",string StrucIdKey="")
        {
            var Dao = GetDao();
            IList<EasyUiTree> list = new List<EasyUiTree>();
            QueryInfo info = new QueryInfo();
            info.CustomSQL = "select * from " + entity;
            if (!string.IsNullOrEmpty(where))
            {
                info.Where.Add("where", " and " + where);

            }
            var tempList = Dao.ExecuteDataSet(info);
            if (tempList.Tables[0].Rows.Count <= 0)
            {
                return new List<EasyUiTree>();
            }

            info = new QueryInfo();
            info.CustomSQL = string.Format("select * from {0} t",  entity);


            var entityList = Dao.ExecuteDataSet(info);
            if (entityList.Tables[0].Rows.Count <= 0)
            {
                return new List<EasyUiTree>();
            }

            //int parentKeyIndex = 0;
            //int valueFieldKeyIndex = 0;
            //int textFieldKeyIndex = 0;

            //valueFieldKeyIndex = 0;
            //textFieldKeyIndex = 1;
            //parentKeyIndex = 2;
            for (var i = 0; i < tempList.Tables[0].Rows.Count; i++)
            {

                DataRow objs = tempList.Tables[0].Rows[i];
                string _parentValue = http://www.mamicode.com/objs[parentKey] != null ? objs[parentKey].ToString() : null;
                string _valueField = objs[valueField] != null ? objs[valueField].ToString() : null;
                string _textField = objs[textField] != null ? objs[textField].ToString() : null;
                if ((string.IsNullOrEmpty(_parentValue)))
                {
                    EasyUiTree c = new EasyUiTree();
                    c.id = _valueField;
                    c.text = _textField;
                    dynamic d=new System.Dynamic.ExpandoObject();
                    if (!string.IsNullOrEmpty(nodeSourceKey))
                    {
                        d.tableRef =objs[nodeSourceKey].ToString();

                    }
                    if (!string.IsNullOrEmpty(StrucIdKey))
                    {
                        d.StrucId = objs[StrucIdKey].ToString();

                    }
                    if (!string.IsNullOrEmpty(levelField))
                    {
                        d.strucLevel = objs[levelField];
                        //c.attributes = new { tableRef = nodeSourceKey, isRoot = false, strucLevel = objs[levelField] };
                    }
                    d.isRoot = true;
                    c.attributes = d;
                    if (HasEntityChildNode(objs, entityList, valueField, textField, parentKey))
                    {
                        c.state = "";
                    }
                    //                (EasyUiTree parent, DataRow objs, DataSet allList, string valueField, string textField, string parentKey, string levelKey = "", string nodeSourceKey = "",string StrucIdKey="")
                    addEntityChildNode(c, objs, entityList, valueField, textField, parentKey, levelField, nodeSourceKey, StrucIdKey);
                    list.Add(c);
                }

            }
            return list;
        }
        private static bool HasEntityChildNode(DataRow objs, DataSet entityList, string valueField, string textField, string parentKey)
        {
            string _valueField = objs[valueField] != null ? objs[valueField].ToString() : null;
            for (var i = 0; i < entityList.Tables[0].Rows.Count; i++)
            {
                DataRow _child = entityList.Tables[0].Rows[i];
                string _parentValue = http://www.mamicode.com/_child[parentKey] != null ? _child[parentKey].ToString() : null;
                if (_valueField == _parentValue)
                {
                    return true;
                }
            }

            return false;
        }


        private static void addEntityChildNode(EasyUiTree parent, DataRow objs, DataSet allList, string valueField, string textField, string parentKey, string levelKey = "", string nodeSourceKey = "",string StrucIdKey="")
        {
            parent.children = new List<EasyUiTree>();
            for (var i = 0; i < allList.Tables[0].Rows.Count; i++)
            {
                DataRow childObj = allList.Tables[0].Rows[i];
                if (childObj[parentKey] != null && !string.IsNullOrEmpty(childObj[parentKey].ToString()) && parent.id == childObj[parentKey].ToString())
                {
                    EasyUiTree c = new EasyUiTree();
                    c.id = childObj[valueField].ToString();
                    c.text = childObj[textField].ToString();
                    dynamic d = new System.Dynamic.ExpandoObject();
                    if (!string.IsNullOrEmpty(nodeSourceKey))
                    {
                        d.tableRef =childObj[nodeSourceKey].ToString();

                    }
                    if (!string.IsNullOrEmpty(StrucIdKey))
                    {
                        d.StrucId = childObj[StrucIdKey].ToString();
                    }
                    if (!string.IsNullOrEmpty(levelKey))
                    {
                        d.strucLevel = childObj[levelKey];
                    }
                    d.isRoot = false;
                    c.attributes = d;
                    //new { tableRef = childObj[nodeSourceKey], isRoot = false, strucLevel = objs[levelKey] };
                    if (HasEntityChildNode(childObj, allList, valueField, textField, parentKey))
                    {
                        c.state = "closed";
                        addEntityChildNode(c, childObj, allList, valueField, textField, parentKey,levelKey,nodeSourceKey,StrucIdKey);

                    }

                    parent.children.Add(c);
                }
            }
            return;
        }
    }
    public class PropertyColumnMappingInfo
    {
        public string PropertyName { get; set; }
        public string ColumnName { get; set; }
        public Type ColumnType { get; set; }
    }

}

 

socket多文件发送(压缩,解压)