/// <summary> /// 向一个Socket发送集合中某个文件的一部分内容 /// </summary> /// <param name="client">已连接的Socket</param> /// <param name="id">文件的标识号</param> /// <param name="offset">发送内容的起始位置</param> /// <param name="length">发送内容的长度</param> public void Send(System.Net.Sockets.Socket client, int id, int offset, int length) { if (this.ContainsKey(id)) { FileInfo fi = this[id]; lock (this) { System.IO.FileStream fs = new System.IO.FileStream(Config.WorkPath + fi.ToString(), System.IO.FileMode.Open); MessageBuffer mb = new MessageBuffer(MessageType.SendFile, id, offset, length); mb.ReadFileBytes(fs); client.Send(mb.GetBytes()); fs.Close(); } } else { MessageBuffer mb = new MessageBuffer(MessageType.RequeryBlockError, id, offset, 0); client.Send(mb.GetBytes()); } }
/// <summary> /// 向一个Socket发送集合中的所有文件 /// </summary> /// <param name="client">已连接的Socket</param> public void Send(System.Net.Sockets.Socket client) { lock (this) { IEnumerator ie = this.GetEnumerator(); while (ie.MoveNext()) { FileInfo fi = ((DictionaryEntry)ie.Current).Value as FileInfo; int id = (int)((DictionaryEntry)ie.Current).Key; lock (this)//防止多线程同时打开文件 { System.IO.FileStream fs = new System.IO.FileStream(Config.WorkPath + fi.ToString(), System.IO.FileMode.Open, System.IO.FileAccess.Read); try { int i = 0; if (FileResume != null && FileResume.ID == id) { i = FileOffSet;//续传文件从续传位置开始 } for (; i < fs.Length; i += Config.FILE_BLOCK_LENGTH) { MessageBuffer mb = new MessageBuffer(MessageType.SendFile, id, i, Config.FILE_BLOCK_LENGTH); mb.ReadFileBytes(fs); client.Send(mb.GetBytes()); } } finally { fs.Close();//确保关闭文件流 } } } } }