多线程写文件

来源:互联网 发布:ahhh网络流行语 编辑:程序博客网 时间:2024/06/06 12:04

创建命令实体类: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))                    {                        var conCollection = dicCon[key];                        con = conCollection.GetConnection();                    }                    else                    {                        ConnectionCollection conCollection = new ConnectionCollection();                        conCollection.Ip = ip;                        conCollection.Port = port;                        dicCon.Add(key, conCollection);                        con = conCollection.GetConnection();                    }                    if (con != null)                    {                        con.UpdateTime = DateTime.Now;                        con.State = State.busy;                    }                    return con;                }            }            catch (Exception ex)            {                throw ex;            }            finally            {                m_mutex.ReleaseMutex();            }        }        public Connection getCon(string key, Connection con)        {            var tt = key.Split('_');            IPAddress ipAddress = IPAddress.Parse(tt[0]);            int port = int.Parse(tt[1]);            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);            // Create a TCP/IP socket.            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            // Connect to the remote endpoint.            client.Connect(remoteEP);            if (con == null)                con = new Connection();            con.State = State.free;            con.SetSocket(client);            return con;        }    }    public class ConnectionCollection    {        private System.Timers.Timer timer = new System.Timers.Timer();        int Max_Conntions = 10;        public ConnectionCollection()        {            FlagHealth = true;            Lst = new List<Connection>();            timer.Interval = 5000;            timer.Elapsed += new System.Timers.ElapsedEventHandler(CheckHealth);            timer.Start();        }        private Socket GetSocket()        {            IPAddress ipAddress = IPAddress.Parse(Ip);            IPEndPoint remoteEP = new IPEndPoint(ipAddress, Port);            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            try            {                client.Connect(remoteEP);                FlagHealth = true;            }            catch            {                FlagHealth = false;            }            return client;        }        public Connection GetConnection()        {            if (!FlagHealth)            {                return null;            }            lock (Lst)            {                for (int i = 0; i < Lst.Count; i++)                {                    var c = Lst[i];                    if (c.State == State.free)                    {                        if (c.IsSocketed())                        {                            return c;                        }                        else                        {                            c.SetSocket( GetSocket());                            return c;                        }                    }                }                while (true)                {                    var temp = Lst.Where(x => x.State == State.free).ToArray();                    if (temp.Length > 0)                    {                        var c = temp[0];                        if (c.IsSocketed() == true)                        {                            return c;                        }                        else                        {                            c.SetSocket(GetSocket());                            return c;                        }                    }                    if (Lst.Count < Max_Conntions)                    {                        Connection con = new Connection();                        con.SetSocket(GetSocket());                        con.State = State.free;                        Lst.Add(con);                        return con;                    }                    Thread.Sleep(50);                }            }        }        void CheckHealth(object sender, EventArgs e)        {            if (!string.IsNullOrEmpty(Ip) && Port != 0)            {                Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                try                {                    client.Connect(Ip, Port);                    FlagHealth = true;                }                catch                {                    FlagHealth = false;                }                finally                {                    if (client != null)                    {                        try                        {                            client.Disconnect(false);                            client.Close();                        }                        catch                        {                        }                    }                }            }        }        public bool IsHealth        {            get            {                return FlagHealth;            }        }        private bool FlagHealth        {            get;            set;        }        public string Key        {            get            {                return Ip + "_" + Port;            }        }        public string Ip        {            get;            set;        }        public int Port        {            get;            set;        }        public List<Connection> Lst        {            get;            set;        }    }    public class Connection    {        public Connection()        {            State = State.free; ;        }        public State State        {            get;            set;        }        public int SendFailReset(byte[] buffer)        {            try            {                return Socket.Send(buffer);            }            catch            {                Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                client.Connect(Socket.RemoteEndPoint);                Socket = client;                return Socket.Send(buffer);            }        }        public int Send(byte [] buffer)        {            return Socket.Send(buffer);        }        public int Receive(byte [] buffer)        {            return Socket.Receive(buffer);        }        public bool IsSocketed()        {            return Socket.Connected;        }        public void CloseSocket()        {             Socket.Disconnect(false);             Socket.Close();        }        public void SetSocket(Socket socket)        {            Socket = socket;        }        private Socket Socket        {            get;            set;        }        public DateTime UpdateTime        {            get;            set;        }        public void Close()        {            State = State.free;        }    }    public enum State    {        free,        busy    }}

创建IO文件操作相关类:FileDeliver

using System;using System.Net;using System.Collections.Generic;using System.Net.Sockets;using System.Threading;using System.Text;using System.IO;using System.Linq;namespace EMNewsInfo{    // State object for receiving data from remote device.    public class StateObject    {        // Client socket.        public Socket workSocket = null;        // Size of receive buffer.        public const int BufferSize = 1024;        // Receive buffer.        public byte[] buffer = new byte[BufferSize];    }    public class FileDeliver    {        // ManualResetEvent instances signal completion.        private ManualResetEvent connectDone =            new ManualResetEvent(false);        private ManualResetEvent sendDone =            new ManualResetEvent(false);        private ManualResetEvent receiveDone =            new ManualResetEvent(false);        private ManualResetEvent receiveResult = new ManualResetEvent(false);        // The response from the remote device.        private String response = String.Empty;        private bool StartClient(object command, out string msg)        {            msg = "";            if (command == null)            {                return false;            }            Command c = command as Command;            Connection client = null;            // Connect to a remote device.            try            {                client = ConnectionPool.GetConnection(c.ServerIp, c.Port);                if (client == null)                {                    msg = c.ServerIp + ":" + c.Port + "建立链接失败";                    return false;                }                // Send test data to the remote device.                var sendCmd = new { Id = c.Id, LocalPath = c.ServerPath, Count = c.Count, Type = c.Type };                Send(client, "<START>" + Newtonsoft.Json.JsonConvert.SerializeObject(sendCmd) + "<EOF>", true);                // Receive the response from the remote device.                Receive(client);                // Write the response to the console.                if (sendCmd.Type == Command.COPY)                {                    //要同步的一端已经完成了同步                    if (response == "true")                    {                        return true;                    }                }                int startIndex = int.Parse(response);                Send(client, c.Data);                Receive(client);                if (response == "true")                {                    return true;                }                else                {                    return false;                }            }            catch (Exception e)            {                msg = e.Message + Environment.NewLine + e.StackTrace;                return false;            }            finally            {                try                {                    if (client != null)                    {                        client.Close();                    }                }                catch                {                }            }        }        private void Receive(Connection client)        {            // Create the state object.            StateObject state = new StateObject();            // Begin receiving the data from the remote device.            int bytesRead = client.Receive(state.buffer);            response = Encoding.GetEncoding("gbk").GetString(state.buffer, 0, bytesRead);            Console.WriteLine("传回数据:" + response);        }        private void Send(Connection client, string data, bool failResetSocket)        {            if (failResetSocket == false)            {                Send(client, data);            }            else            {                // Convert the string data to byte data using ASCII encoding.                byte[] byteData = Encoding.GetEncoding("gbk").GetBytes(data);                // Begin sending the data to the remote device.                //client.BeginSend(byteData, 0, byteData.Length, 0,                //    new AsyncCallback(SendCallback), client);                Send(client, byteData, failResetSocket);                sendDone.Set();            }        }        private void Send(Connection client, String data)        {            // Convert the string data to byte data using ASCII encoding.            byte[] byteData = Encoding.GetEncoding("gbk").GetBytes(data);            // Begin sending the data to the remote device.            //client.BeginSend(byteData, 0, byteData.Length, 0,            //    new AsyncCallback(SendCallback), client);            Send(client, byteData);            sendDone.Set();        }        private void Send(Connection client, string path, long startIndex)        {            FileStream fs = null;            byte[] buffer = new byte[102400];            FileInfo sendFile = new FileInfo(path);            using (fs = sendFile.OpenRead())            {                fs.Position = startIndex;                int tmpcount = 0;                while ((tmpcount = fs.Read(buffer, 0, buffer.Length)) > 0)                {                    if (tmpcount != buffer.Length)                    {                        byte[] endbuffer = new byte[tmpcount];                        Array.Copy(buffer, endbuffer, tmpcount);                        Send(client, endbuffer);                        break;                    }                    Send(client, buffer);                }            }        }        private void Send(Connection client, byte[] data, bool failResetClient)        {            if (failResetClient == false)            {                Send(client, data);            }            else            {                client.SendFailReset(data);            }        }        private void Send(Connection client, byte[] data)        {            client.Send(data);        }        public static bool StartTranCommand(byte[] data, string serverPath, out string msg)        {            string fileServer = System.Configuration.ConfigurationManager.AppSettings["FileServer"];            string[] servers = fileServer.Split('|');            return StartTranCommand(data, serverPath, servers, out msg);        }        /// <summary>        /// 传送一个文件        /// </summary>        /// <param name="data">要传送文件的字节数组</param>        /// <param name="serverPath">服务器端的路劲</param>        /// <param name="servers">服务器列表</param>        /// <param name="msg">错误消息</param>        /// <returns></returns>        public static bool StartTranCommand(byte[] data, string serverPath, string[] servers, out string msg)        {            msg = string.Empty;            FileDeliver tt = new FileDeliver();            foreach (var c in servers)            {                var t = c.Split(':');                var server = new { ip = t[0], port = int.Parse(t[1]) };                Command command = new Command();                command.Id = Guid.NewGuid().ToString();                command.Count = data.Length;                command.CTime = DateTime.Now;                command.Data = data;                command.Port = server.port;                command.ServerIp = server.ip;                command.ServerPath = serverPath;                command.Type = "copy";                if (!tt.StartClient(command, out msg))                {                    return false;                }            }            return true;        }    }}

写文件方法:

/// <summary>/// 创建列表信息文件/// </summary>/// <param name="_path"></param>/// <param name="content"></param>private void CreateListFile(string _path, string content){      byte[] datas = System.Text.Encoding.GetEncoding("utf-8").GetBytes(content);      string msg = "";      FileDeliver.StartTranCommand(datas, _path, out msg);}
多线程方法:

        List<string> codes = new List<string>();        object locker = new object();        /// <summary>        /// 多线程生成文件        /// </summary>        private void Woker()        {            string surl = System.Configuration.ConfigurationManager.AppSettings["ServerUrl"];            string _dir = "D:\\wwwroot\\down\\xg\\";            bool bWork = true;            while (bWork)            {                string code = "";                lock (codes)                {                    if (codes == null || codes.Count == 0)                    {                        bWork = false;                    }                    else                    {                        code = codes[0];                        codes.RemoveAt(0);                    }                }                if (code != "")                    CreateStockNews(code, surl, _dir);            }            lock (locker)            {                ClearInfo();            }        }

/// <summary>        /// 生成个股        /// </summary>        /// <param name="code"></param>        private void CreateStockNews(string code, string surl, string _dir)        {            Console.WriteLine("获取" + code + "的个股资讯");            string url = surl + "/news/EPNewsInfo.ashx?action=GetStockNewsInfo&code=" + code;            string resuls = OperMethod.GetPageByUrl(url, "gb2312");            List<EMNewsInfoModel> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<EMNewsInfoModel>>(resuls);            string stockfile = _dir + code + "\\";            Console.WriteLine("生成" + code + "的个股资讯详细信息");            if (list != null && list.Count > 0)            {                if (!File.Exists(stockfile))                {                    Directory.CreateDirectory(stockfile);                }                CreateFile(stockfile, list);            }}

/// <summary>        /// 清除缓存        /// </summary>        private void ClearInfo()        {            Console.WriteLine("清除缓存资讯信息");            string _url = "http://ccms.chinacache.com/index.jsp?user=emstock&pswd=Emstock123&ok=ok&dirs=http://down3.emstock.com.cn/xg/";            string _content = OperMethod.GetPageByUrl(_url, "Gb2312");            _url = "http://ccms.chinacache.com/index.jsp?user=emstock&pswd=Emstock123&ok=ok&dirs=http://down3.emstock.com.cn/dingpan/";            _content = OperMethod.GetPageByUrl(_url, "Gb2312");        }



原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 学信网注册身份证重复怎么办 学历和学位认证怎么办 假学历无法认证怎么办 学历认证没照片怎么办? 毕业证封皮丢了怎么办 留服认证不了怎么办 无公害认证书怎么办 假学历认证报告怎么办 留学要求寄原件怎么办 干部小三怀孕怎么办? 小三的孩子怎么办 把小三打住院了怎么办 小月子没人伺候怎么办 寝室室友有狐臭怎么办 室友在寝室养猫怎么办 和直接领导不合怎么办 房产共有人去世怎么办 发现邪教宣传内容怎么办 说课时两个课时怎么办 投稿文章被拒绝怎么办 中立性细胞偏低怎么办? 孩子爱告状老师怎么办 高中学不好数学怎么办 想做老师应该怎么办 教师职称换学校怎么办 大四差选修学分怎么办 尔雅通识课学分没修满怎么办 大学全英文授课怎么办 小孩脑部有囊肿怎么办 防震期间门应该怎么办 在家待着没意思怎么办 人户分离上学怎么办 小孩上学没人接送怎么办 宝宝上学没人接送怎么办 上海浦东新区酒类许可证怎么办 金税盘里报税处理打不开怎么办 惠民卡到期了怎么办 遇到不拴狗链的主人怎么办 平安福没钱续保怎么办 提前很久到机场怎么办 机场来早了怎么办