目录

Implementing the Function of Suspending/Resuming Requests and Resuming Transfer

Constraints

The capability of suspending/resuming requests and resuming transfer supports phones, 2-in-1 devices, tablets, and wearables. Starting from version 5.1.1(19), it is also supported on TVs.

Request Suspension and Resumption

[h2]Use Cases

Remote Communication Kit provides robust capabilities for implementing request suspension and resumption. This feature applies for both request sending and receiving processes.

[h2]Example

  1. Import the required modules.

    import { rcp } from '@kit.RemoteCommunicationKit';
    import { util } from '@kit.ArkTS';
    import { BusinessError } from '@kit.BasicServicesKit';
  2. Define the debugging information interface, debugging information source type, and debugging information serialization function to serialize debugging information into a StringifiedDebugInfo array. The function first retrieves the debugging information based on the type of infoSource, then uses TextDecoder to decode the data field of the debugging information into a string, and returns an array containing the decoded debugging information.

    // Define the request URL. (Change the value in the example based on your needs.)
    const HTTP_SERVER_POST: string = 'https://example.com/anything';
    // Define the debugging information interface.
    interface StringFeildDebugInfo {
      type: rcp.DebugEvent;
      data: string;
    };
    // Define the debugging information source type.
    type DebugInfoSource = undefined | rcp.DebugInfo[] | rcp.Response;
    
    // Define the debugging information serialization function.
    function debugInfoStringify(infoSource: DebugInfoSource): StringFeildDebugInfo[] {
      const debugInfo = Array.isArray(infoSource)
        ? (infoSource as rcp.DebugInfo[])
        : (infoSource as rcp.Response).debugInfo;
    
      if (!debugInfo) {
        return [];
      }
    
      const decoder = util.TextDecoder.create('utf-8');
      return debugInfo.map((i: rcp.DebugInfo): StringFeildDebugInfo => {
        return {
          type: i.type,
          data: decoder.decodeToString(new Uint8Array(i.data)).trim(),
        };
      });
    }
  3. Obtain sending suspension and resumption events from the debugging information.

    function getSendPausedEvents(debugInfo: DebugInfoSource) {
      return debugInfoStringify(debugInfo).filter((i) => i.data.startsWith('[[RCP]]: Pause sending'));
    }
    
    function getSendResumedEvents(debugInfo: DebugInfoSource) {
      return debugInfoStringify(debugInfo).filter((i) => i.data.startsWith('[[RCP]]: Resume sending'));
    }
  4. Define the function for initiating requests.

    const sendingPauseByTimeout = async (done: Function): Promise<void> => {
      try {
        const session = rcp.createSession();
        const request = new rcp.Request(HTTP_SERVER_POST);
        // Define the sending suspension policy. Set **kind** to **timeout** and **timeoutMs** to **1**, in milliseconds.
        const sendPolicy: rcp.SendingPausePolicy = {
          kind: 'timeout',
          timeoutMs: 1,
        };
        // Define the suspension policy. The **sending** field references the **sendPolicy** parameter defined above.
        const pausePolicy: rcp.PausePolicy = {
          sending: sendPolicy,
        };
        // Define request configurations, including the transfer policy and tracing information.
        request.configuration = {
          transfer: {
            pausePolicy: pausePolicy,
          },
          tracing: {
            infoToCollect: {
              textual: true,
            },
          },
        };
        // Define the request body data.
        const data = 'TestData';
        // Set the request header. The **Content-Length** field indicates the length of the request body.
        request.headers = {
          'Content-Length': data.length.toString(),
        };
        // Define a Boolean flag to control the generation of the request body.
        let isReadCompleted = false;
        // Set the request method to POST.
        request.method = 'POST';
        // Define the function for generating the request body content. If read is true, an empty ArrayBuffer is returned. Otherwise, an ArrayBuffer containing the request body data is generated.
        request.content = (maxSize) => {
          if (isReadCompleted) {
            return new ArrayBuffer(0);
          }
          isReadCompleted = true;
          const buffer = new ArrayBuffer(data.length);
          util.TextEncoder.create('utf-8').encodeIntoUint8Array(data, new Uint8Array(buffer));
          return buffer;
        };
    
        // Send a request and wait for the response.
        const response = await session.fetch(request)
    
        // Obtain sending suspension and resumption events from the response debugging information.
        const pausedEvents = getSendPausedEvents(response);
        const resumedEvents = getSendResumedEvents(response);
        // ...
    
        // Close the session.
        session.close();
        // Execute the callback function.
        done();
      } catch (err) {
        console.error(`error code is ${err.code}, error data is ${err.data}`);
      }
    }

Resumable Transfer

[h2]Use Cases

In scenarios where data requests need to be resumed, you can define the from and to attributes of the TransferRange object to control the data range to be intercepted. Downloaded content can be accurately extracted and appended to the target file, ensuring data integrity and consistency, and enabling you to flexibly manage and resume downloads.

[h2]Example

  1. Import the required modules.

    import { rcp } from '@kit.RemoteCommunicationKit';
    import { util } from '@kit.ArkTS';
    import { BusinessError } from '@kit.BasicServicesKit';
  2. Create a session, define the request URL, create a request, and define a variable to record the total size of the file to be downloaded.

    // Create a session.
    let session: rcp.Session | null = rcp.createSession();
    // Define the server URL.
    const kHttpServerAddress = 'http://www.example.com/fetch';
    // Create a request.
    const request = new rcp.Request(kHttpServerAddress, 'GET');
    // Define a variable to record the size of the file to be downloaded.
    let totalSize = 0;
    // Define a variable that stores the last transfer position.
    let lastTransferPosition = 0;
  3. Write a function to obtain the size of the file to be downloaded. There are multiple methods to obtain the size. You can choose one based on your needs. In this example, the total size of the file to be downloaded is obtained from the content-range field in the header of the response data.

    /**
     * Obtain the size of the file to be downloaded.
     *
     * @returns File size.
     */
    async getTotalSize(): Promise<number> {
      if (this.request == null || this.session == null) {
        return this.totalSize;
      }
      this.request.transferRange = { from: 0, to: 1 };
      try {
        let rep = await this.session?.fetch(this.request);
        if (rep) {
          // Extract the size of the file from the content-range field in the header of the response data.
          let contentRange = rep.headers['content-range'];
          let sizeStr = contentRange ? contentRange.substring(contentRange.indexOf('\/') + 1, contentRange.length) : '0';
          this.totalSize = Number(sizeStr);
        }
      } catch (err) {
        console.error(`getTotalSize error code is ${err.code}, error data is ${err.data}`);
      }
      console.info(`getTotalSize totalSize: ${this.totalSize.toString()}`);
      return this.totalSize;
    }
  4. Write a function for downloading a file based on the transfer range.

    /**
     * Download a file based on the transfer range.
     *
     * @param from - Start position of the transfer range.
     * @param to - End position of the transfer range.
     */
    downloadTransfer(from: number, to: number) {
      if (this.request == null || this.session == null) {
        return;
      }
      // ...
      // Set the requested data transfer range.
      this.request.transferRange = { from: from, to: to };
      this.session?.fetch(this.request).then((rep) => {
        if (rep.body) {
          // Process the response. You can save the file to the local host here.
          console.info(`Response succeeded: ${JSON.stringify(rep.headers)}`);
          // Start position of the next transfer = Position of the previous transfer + Length of the data transferred this time
          this.lastTransferPosition += rep.body.byteLength;
          if (this.lastTransferPosition < this.totalSize) {
            // Calculate the end position of the next transfer range.
            const nextTo = Math.min(this.lastTransferPosition + 100, this.totalSize);
            // Recursively call the function to continue downloading the next segment of data.
            this.downloadTransfer(this.lastTransferPosition, nextTo);
          } else {
            console.info('Response succeeded, completed.');
          }
          // ...
        }
      }).catch((err: BusinessError) => {
        console.error(`Continue transfer error: code is ${err.code}, message is ${err.message}`);
      });
    }
  5. Start downloading data.

    if (!session) {
      session = rcp.createSession();
    }
    // Reset the transfer position to zero.
    lastTransferPosition = 0;
    // Obtain the total size of the file to be downloaded.
    await this.getTotalSize();
    // Calculate the end position of the transfer range.
    const nextTo = Math.min(lastTransferPosition + 100, totalSize);
    // Start downloading.
    this.downloadTransfer(lastTransferPosition, nextTo);
  6. Suspend data download.

    /**
     * Suspend data download.
     */
    async pauseDownload() {
      // ...
      // Cancel the download request.
      this.session?.cancel(this.request);
    }
  7. Resume data download.

    /**
     * Resume data download.
     */
    async resumeDownload() {
      // Calculate the end position of the transfer range.
      const nextTo = Math.min(this.lastTransferPosition + 100, this.totalSize);
      // Start downloading.
      this.downloadTransfer(this.lastTransferPosition, nextTo);
    }
  8. Stop data download.

    // Cancel the download request.
    this.session?.cancel(this.request);
    // Close the session.
    this.session?.close();
    this.session = null;