Recently, a few friends asked me how to implement functions similar to QQ offline files. If you don't want to answer questions one by one, write a blog post to fully explain this question.
The so-called "offline file" means that when the recipient is offline, the sender first transfers the file to the server and temporarily saves it on the server. When the receiver is online, the server sends the file to him. Of course, to implement the function of offline files, the most basic premise is to implement the function of transferring files first. We will base on the function of transferring files provided by ESFramework, complete a basic offline file function step by step.
Next we will introduce the corresponding design and implementation of the program based on the sequence of actions when users use offline files.
1. The client sends offline files
When you select a file and click "Send offline file", the object is sent to the server. You can directly use the BeginSendFile method of IFileOutter:
/// <Summary> /// the sender prepares to send a file (folder ).
/// </Summary> /// <param name = "accepterID"> receive file (folder) user ID </param> /// <param name = "fileOrDirPath"> file to be sent (folder) </param> /// <param name = "comment"> other additional remarks. If it is in a service similar to FTP, this parameter can be a save file (folder) </param> /// <param name = "projectID"> return the ID of the file transfer project </param> void BeginSendFile (string accepterID, string fileOrDirPath, string comment, out string projectID );
If the parameter accepterID is null, it indicates that the recipient of the file is the server. So how should we differentiate that this is not a file received by the server end, but an offline file to another user? Here, we can use the comment parameter. For example, if the comment parameter is null, it indicates a normal upload file. If the comment parameter is not null, it indicates an offline file, and its value is the ID of the final receiver of the file. (Of course, if the comment parameter is used for other purposes in your project, we can further expand it and add some labels so that it can mark offline files ).
In the example below, the test.txt file is sent offline to aa01.
String filePath =...; // path of the file to be sent string projectID = null; fileOutter. BeginSendFile (null, filePath, "aa01", out projectID );
2. The server receives offline files.
After the client calls the BeginSendFile method to send a file request, the server triggers the FileRequestReceived event of IFileController. Similarly, when the event comment parameter is not null, it indicates an offline file. Before replying to the client's consent to receiving a file, we need to save the information about the offline file. Here we use the OfflineFileItem class to encapsulate this information.
/// <Summary> /// offline file entry /// </summary> public class OfflineFileItem {/// <summary> // unique ID of the entry, database auto-incrementing sequence, primary key. /// </Summary> public string AutoID {get; set ;}/// <summary> // name of the offline file. /// </Summary> public string FileName {get; set ;}/// <summary> /// file size. /// </Summary> public ulong FileLength {get; set ;}/// <summary> // The sender ID. /// </Summary> public string SenderID {get; set ;}/// <summary> // receiver ID. /// </Summary> public string AccepterID {get; set ;}/// <summary> /// temporary path for storing offline files on the server. /// </Summary> public string RelayFilePath {get; set ;}}
With the definition of OfflineFileItem, we can handle the FileRequestReceived event of IFileController.
RapidServerEngine. fileController. fileRequestReceived + = new CbFileRequestReceived (bytes); ObjectManager <string, OfflineFileItem> offlineFileItemManager = new ObjectManager <string, OfflineFileItem> (); // The ObjectManager class can be considered a thread-safe Dictionary. Void fileController_FileRequestReceived (string projectID, string senderID, string fileName, ulong totalSize, ResumedProjectItem resumedFileItem, string comment) {string saveFilePath = "...... "; // get the path of the stored file if (comment! = Null) // according to the Conventions, comment is not null, which indicates an offline file, and its value is the ID of the final receiver. {String accepterID = comment; OfflineFileItem item = new OfflineFileItem (); item. accepterID = accepterID; item. fileLength = totalSize; item. fileName = fileName; item. senderID = senderID; item. relayFilePath = saveFilePath; offlineFileItemManager. add (projectID, item) ;}// return the consent to the client and start preparing to receive the file. RapidServerEngine. FileController. BeginReceiveFile (projectID, saveFilePath );}
The above Code does three things:
(1) obtain the path for storing files according to a certain policy.
(2) create an offline File Information entry and save it in the memory.
(3) reply to the client and prepare to receive files.
It is important to note the first point. For small projects, we can store all offline files in a directory on the server. For large projects, DFS (Distributed File System) is generally used to store these temporary offline files.
After receiving a reply from the server, the client will formally start transferring files. if the transfer is interrupted due to some reason during the transfer, the server will trigger the FileTransDisruptted event of IFileController. FileReceivingEvents. In this event processing function, we remove the corresponding offline File Information entries from the memory:
rapidServerEngine.FileController.FileReceivingEvents.FileTransDisruptted += new CbGeneric<TransferingProject, FileTransDisrupttedType>(fileReceivingEvents_FileTransDisruptted); void fileReceivingEvents_FileTransDisruptted(TransferingProject project, FileTransDisrupttedType type) { offlineFileItemManager.Remove(project.ProjectID); }
If the file is transmitted normally, the server triggers the FileTransCompleted event of IFileController. FileReceivingEvents. In this case, the corresponding offline File Information entries are transferred from memory to the database to prevent information loss during server restart:
rapidServerEngine.FileController.FileReceivingEvents.FileTransCompleted += new CbGeneric<TransferingProject>(fileReceivingEvents_FileTransCompleted); IOfflineFilePersister offlineFilePersister = ......; void fileReceivingEvents_FileTransCompleted(TransferingProject project) { OfflineFileItem item = offlineFileItemManager.Get(project.ProjectID); offlineFilePersister.Add(item); offlineFileItemManager.Remove(project.ProjectID); }
We designed the IOfflineFilePersister interface to interact with the OfflineFileItem table in the database.
Public interface IOfflineFilePersister {// <summary> /// save an offline file entry to the database. /// </Summary> void Add (OfflineFileItem item); // <summary> /// Delete the entry with the primary key value ID from the database. /// </Summary> void Remove (string id); /// <summary> // extract all offline file entries of the specified user from the database. /// </Summary> List <OfflineFileItem> GetByAccepter (string accepterID );}
We can use ADO. NET or EntityFramework to implement the above interface.
3. the server sends an offline file to the final receiver.
When a real receiver goes online, the server sends the related offline files to the receiver. By booking the SomeOneConnected event of UserManager, we know the time when the user is online.
rapidServerEngine.UserManager.SomeOneConnected += new CbGeneric<UserData>(userManager_SomeOneConnected); void userManager_SomeOneConnected(UserData data) { List<OfflineFileItem> list = offlineFilePersister.GetByAccepter(data.UserID); if (list != null) { foreach (OfflineFileItem item in list) { string projectID = null ; rapidServerEngine.FileController.BeginSendFile(item.AccepterID, item.RelayFilePath, item.SenderID, out projectID); offlineFilePersister.Remove(item.AutoID); File.Delete(item.RelayFilePath); } } }
The above Code does three things:
(1) Find all offline File Information entries whose recipients are logged on to the database.
(2) Send offline files to this user one by one
(3) Delete the corresponding entries from the database and delete the corresponding offline files from the disk.
In fact, at (3), we can perform the delete operation only after the file is sent. In this way, it is possible to resend the message in case of unexpected interruption.
When receiving a file request from the server, the client triggers the IFileOutter FileRequestReceived event. You can also determine whether the request is an offline file based on the content of the comment parameter. The subsequent steps are quite easy to implement and will not be described here.
This article briefly describes the main idea and basic model for implementing the offline file function. In actual project development, we can further improve this model based on specific requirements, including many details and exception handling needs to be added.