/// <summary> /// Processes a streaming file packet, building a file as bytes are received. /// Files received must be content packages for security reasons. /// </summary> /// <param name="packet"></param> private void ProcessStreamingFilePacket(StreamingFilePacket packet) { if (Path.GetExtension(packet.FileName) == FileExtensionFactory.GetFileExtension(FileTypeEnum.ContentPackage) && FileStreamStatus == FileStreamerStatusEnum.Downloading) { string filePath = DirectoryPaths.ContentPackageDirectoryPath + packet.FileName; if (!File.Exists(filePath)) { File.Create(filePath).Close(); } LastReceivedFile = packet.FileName; using (FileStream fileStream = new FileStream(filePath, FileMode.Append)) { fileStream.Write(packet.FileBytes, 0, (int)packet.FileBytes.Length); } // If this is the end of the file, we need to remove it from the list // and request the next file from the server. if (packet.IsEndOfFile) { MissingFiles.Remove(packet.FileName); if (MissingFiles.Count > 0) { FileStreamStatus = FileStreamerStatusEnum.Stopped; RequestFileFromServer(MissingFiles[0]); } else { FileStreamStatus = FileStreamerStatusEnum.Complete; } } } }
/// <summary> /// Handles streaming the next segment of files to users downloading content packages. /// </summary> private void StreamFilesToClients() { List<NetConnection> connectionList = FileTransferClients.Keys.ToList(); foreach (NetConnection currentConnection in connectionList) { FileTransferProgress clientProgress = FileTransferClients[currentConnection]; if (File.Exists(clientProgress.FilePath)) { using (FileStream fileStream = new FileStream(clientProgress.FilePath, FileMode.Open)) { bool isEndOfFile = false; int numberOfBytesToSend = GameServerConfiguration.FileTransferBufferSize; int numberOfBytesRemaining = (int)fileStream.Length - clientProgress.BytesSent; if (numberOfBytesRemaining < GameServerConfiguration.FileTransferBufferSize) { numberOfBytesToSend = numberOfBytesRemaining; isEndOfFile = true; } fileStream.Position = clientProgress.BytesSent; byte[] bytesToSend = new byte[numberOfBytesToSend]; fileStream.Read(bytesToSend, 0, numberOfBytesToSend); StreamingFilePacket packet = new StreamingFilePacket { FileName = Path.GetFileName(clientProgress.FilePath), FileBytes = bytesToSend, IsEndOfFile = isEndOfFile }; Agent.SendPacket(packet, currentConnection, NetDeliveryMethod.ReliableOrdered); clientProgress.BytesSent += numberOfBytesToSend; // Remove client from streaming list if this was the last part of the file to be sent if (clientProgress.BytesSent >= (int)fileStream.Length) { FileTransferClients.Remove(currentConnection); } } } } }