void dealer() { DataSender ds = new DataSender(order.LocalIPE, order.SenderIPE); switch (order.OrderName) { case "GetFile": ds.SendFile(order.Root, order.Parameter[0]); break; case "XML": ds.SendFile("Update.Xml"); break; case "GetServerTime": ds.SendOrder("ServerTime", DateTime.Now.ToString()); break; case "ServerTime": Console.WriteLine(order.Parameter[0]); break; case "FileData": SaveFile(); break; } }
void download() { Socket sockets = null; //用于传输的Socket类。 byte[] fileData = null; //文件数据。 byte[] tempBytes = null; //临时缓冲数据。 DataDownloadEvenetArgs e = new DataDownloadEvenetArgs(); e.RecieverIp = localIpe; e.SenderIp = remoteIpe; try { sockets = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sockets.Bind(localIpe); sockets.Listen(5); //发送连接请求, 某路径没数据,那么变为等待状态。 if (filePath != null && filePath.Length > 0) { DataSender ds = new DataSender(localIpe, remoteIpe); if (filePath.ToLower() == "xml") { ds.SendOrder("XML"); } else { ds.SendOrder("GetFile", filePath); } } //等待接收数据。 Socket newSocket = sockets.Accept(); //先读取头文件。 tempBytes = new byte[1024]; newSocket.Receive(tempBytes); NetOrder no = new NetOrder(tempBytes); e.StartTime = DateTime.Now; if (no.OrderName == "FileData") { //开始接收数据。 downloading = true; filePath = no.Parameter[0]; fileSize = int.Parse(no.Parameter[1]); //再读取后面的数据。t用于表示每次读取到的数据长度。 MemoryStream ms = new MemoryStream(); tempBytes = new byte[blockSize]; int t = 1; while (t > 0) { t = newSocket.Receive(tempBytes); downloadedSize += t; ms.Write(tempBytes, 0, t); } //接收数据到fileData fileData = ms.ToArray(); e.EndTime = DateTime.Now; //关闭所有相关资源。 newSocket.Close(); sockets.Close(); ms.Close(); downloading = false; //保存文件。 SaveFile(fileData); completeDownload = true; e.Data = fileData; e.Message = "文件接收成功。"; } else if (no.OrderName == "Error") { e.Message = no.Parameter[0]; e.Data = null; } } catch (Exception e1) { e.Data = null; e.Message = e1.Message; e.EndTime = DateTime.Now; } if (DownloadComplete != null) { DownloadComplete(this, e); } }