• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# IPC and RPC Development (ArkTS)
2<!--Kit: IPC Kit-->
3<!--Subsystem: Communication-->
4<!--Owner: @xdx19211@luodonghui0157-->
5<!--Designer: @zhaopeng_gitee-->
6<!--Tester: @maxiaorong2-->
7<!--Adviser: @zhang_yixin13-->
8
9## When to Use
10
11IPC/RPC is used to implement object communication across processes (one-to-one mapping between the client proxy and the server stub).
12
13## How to Develop
14
15> **NOTE**
16>
17> - Currently, third-party applications cannot implement ServiceExtensionAbility. The UIAbility component of a third-party application can connect to the ServiceExtensionAbility provided by the system through [Context](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
18>
19> - Application scenario constraints: The client is a third-party or system application, and the server is a system application or service.
20
21### Creating ServiceExtensionAbility to Implement the Server
22
23Create a ServiceExtensionAbility as follows:
24
251. In the **ets** directory of a module in the project, right-click and choose **New > Directory** to create a directory named **ServiceExtAbility**.
26
272. In the **ServiceExtAbility** directory, right-click and choose **New > ArkTS File** to create a file named **ServiceExtAbility.ets**.
28
29    ```
30      ├── ets
31      │ ├── ServiceExtAbility
32      │ │   ├── ServiceExtAbility.ets
3334    ```
35
363. In the **ServiceExtAbility.ets** file, import the dependency package of the ServiceExtensionAbility. The custom class inherits the ServiceExtensionAbility and implements lifecycle callbacks. Define a stub class that inherits from [rpc.RemoteObject](../reference/apis-ipc-kit/js-apis-rpc.md#remoteobject) and implement the [onRemoteMessageRequest](../reference/apis-ipc-kit/js-apis-rpc.md#onremotemessagerequest9) method to process requests from the client. In the **onConnect** lifecycle callback, create the defined stub object and return it.
37
38   ```ts
39    import { ServiceExtensionAbility, Want } from '@kit.AbilityKit';
40    import { rpc } from '@kit.IPCKit';
41    import { hilog } from '@kit.PerformanceAnalysisKit';
42
43    // Define the server.
44    class Stub extends rpc.RemoteObject {
45      constructor(descriptor: string) {
46        super(descriptor);
47      }
48      // The service overrides the onRemoteMessageRequest method to process the client request.
49      onRemoteMessageRequest(code: number, data: rpc.MessageSequence, reply: rpc.MessageSequence, option: rpc.MessageOption): boolean | Promise<boolean> {
50        // Process requests sent from the client based on the code.
51        switch (code) {
52          case 1:
53            {
54              // Read data based on the client write sequence. For details, see the service logic.
55              // This is an example of sending information from the client to the server.
56              data.readString();
57              reply.writeString('huichuanxinxi');
58            }
59        }
60        return true;
61      }
62    }
63
64    // Define the background service.
65    export default class ServiceAbility extends ServiceExtensionAbility {
66      onCreate(want: Want): void {
67        hilog.info(0x0000, 'testTag', 'onCreate');
68      }
69
70      onRequest(want: Want, startId: number): void {
71        hilog.info(0x0000, 'testTag', 'onRequest');
72      }
73
74      onConnect(want: Want): rpc.RemoteObject {
75        hilog.info(0x0000, 'testTag', 'onConnect');
76        // Return a stub object, through which the client can communicate with the ServiceExtensionAbility.
77        return new Stub('rpcTestAbility');
78      }
79
80      onDisconnect(want: Want): void {
81        hilog.info(0x0000, 'testTag', 'onDisconnect');
82      }
83
84      onDestroy(): void {
85        hilog.info(0x0000, 'testTag', 'onDestroy');
86      }
87    }
88   ```
89
90### Connecting to the Service and Obtaining the Service Proxy
91
92**Creating want and connect**
93
941. Create a **want** variable, and specify the bundle name and component name of the application where the ability is located. If cross-device communication is involved, also specify the network ID of the target device, which can be obtained through distributedDeviceManager.
95
962. Create a **connect** variable, and specify the callback that is called when the binding is successful, the binding fails, or the ability is disconnected.
97
98  In IPC, create the variables **want** and **connect**.
99  ```ts
100    import { Want, common } from '@kit.AbilityKit';
101    import { rpc } from '@kit.IPCKit';
102    import { hilog } from '@kit.PerformanceAnalysisKit';
103
104    let proxy: rpc.IRemoteObject | undefined;
105
106    let want: Want = {
107      // Enter the bundle name and ability name.
108      bundleName: "ohos.rpc.test.server",
109      abilityName: "ohos.rpc.test.server.ServiceAbility",
110    };
111    let connect: common.ConnectOptions = {
112      onConnect: (elementName, remoteProxy) => {
113        hilog.info(0x0000, 'testTag', 'RpcClient: js onConnect called');
114        proxy = remoteProxy;
115      },
116      onDisconnect: (elementName) => {
117        hilog.info(0x0000, 'testTag', 'RpcClient: onDisconnect');
118      },
119      onFailed: () => {
120        hilog.info(0x0000, 'testTag', 'RpcClient: onFailed');
121      }
122    };
123  ```
124
125  In RPC, create the variables **want** and **connect**.
126  ```ts
127    import { Want, common } from '@kit.AbilityKit';
128    import { rpc } from '@kit.IPCKit';
129    import { hilog } from '@kit.PerformanceAnalysisKit';
130    import { distributedDeviceManager } from '@kit.DistributedServiceKit';
131    import { BusinessError } from '@kit.BasicServicesKit';
132
133    let dmInstance: distributedDeviceManager.DeviceManager | undefined;
134    let proxy: rpc.IRemoteObject | undefined;
135    let deviceList: Array<distributedDeviceManager.DeviceBasicInfo> | undefined;
136    let networkId: string | undefined;
137    let want: Want | undefined;
138    let connect: common.ConnectOptions | undefined;
139
140    try{
141      dmInstance = distributedDeviceManager.createDeviceManager("ohos.rpc.test");
142    } catch(error) {
143      let err: BusinessError = error as BusinessError;
144      hilog.error(0x0000, 'testTag', 'createDeviceManager errCode:' + err.code + ', errMessage:' + err.message);
145    }
146
147    // Use distributedDeviceManager to obtain the network ID of the target device.
148    if (dmInstance != undefined) {
149      try {
150        deviceList = dmInstance.getAvailableDeviceListSync();
151        if (deviceList.length !== 0) {
152          networkId = deviceList[0].networkId;
153          want = {
154            bundleName: "ohos.rpc.test.server",
155            abilityName: "ohos.rpc.test.service.ServiceAbility",
156            deviceId: networkId,
157          };
158          connect = {
159            onConnect: (elementName, remoteProxy) => {
160              hilog.info(0x0000, 'testTag', 'RpcClient: js onConnect called');
161              proxy = remoteProxy;
162            },
163            onDisconnect: (elementName) => {
164              hilog.info(0x0000, 'testTag', 'RpcClient: onDisconnect');
165            },
166            onFailed: () => {
167              hilog.info(0x0000, 'testTag', 'RpcClient: onFailed');
168            }
169          };
170        }
171      }catch(error) {
172        let err: BusinessError = error as BusinessError;
173        hilog.error(0x0000, 'testTag', 'createDeviceManager err:' + err);
174      }
175    }
176  ```
177
178**Connection Service**
179
180  In the FA model, the [connectAbility](../reference/apis-ability-kit/js-apis-ability-featureAbility.md#featureabilityconnectability7) API is used to connect to an ability.
181
182  <!--code_no_check_fa-->
183  ```ts
184    import { featureAbility } from '@kit.AbilityKit';
185
186    // Save the connection ID, which will be used when the ability is disconnected.
187    let connectId = featureAbility.connectAbility(want, connect);
188  ```
189
190  In the stage model, the [connectServiceExtensionAbility](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#connectserviceextensionability) API of **common.UIAbilityContext** is used to connect to an ability.
191  In the sample code provided in this topic, **this.getUIContext().getHostContext()** is used to obtain **UIAbilityContext**, where **this** indicates a UIAbility instance inherited from **UIAbility**. To use **UIAbilityContext** APIs on pages, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
192
193  <!--code_no_check-->
194  ```ts
195
196    let context: common.UIAbilityContext = this.getUIContext().getHostContext(); // UIAbilityContext
197    // Save the connection ID, which will be used when the ability is disconnected.
198    let connectId = context.connectServiceExtensionAbility(want,connect);
199   ```
200
201### Sending Information from Client to Server
202
203   After the service is successfully connected, you can use the **onConnect** callback to obtain the proxy object of the server. Then, use the proxy to call the [sendMessageRequest](../reference/apis-ipc-kit/js-apis-rpc.md#sendmessagerequest9-2) method to initiate a request. When the server processes the request and returns data, you can receive the result returned by a promise contract (used to indicate the success or failure result value of an asynchronous operation).
204
205   ```ts
206    import { rpc } from '@kit.IPCKit';
207    import { hilog } from '@kit.PerformanceAnalysisKit';
208
209    // The proxy in this code snippet is obtained from the onConnect callback after the service is successfully connected.
210    let proxy: rpc.IRemoteObject | undefined;
211
212    // Use the promise contract.
213    let option = new rpc.MessageOption();
214    let data = rpc.MessageSequence.create();
215    let reply = rpc.MessageSequence.create();
216    // Write parameters in data. The following uses the string as an example.
217    data.writeString("hello world");
218
219    if (proxy != undefined) {
220      proxy.sendMessageRequest(1, data, reply, option)
221        .then((result: rpc.RequestResult) => {
222          if (result.errCode != 0) {
223            hilog.error(0x0000, 'testTag', 'sendMessageRequest failed, errCode: ' + result.errCode);
224            return;
225          }
226          // Read the result from result.reply.
227          // The following is an example of creating a ServiceExtensionAbility on the server.
228          result.reply.readString();
229        })
230        .catch((e: Error) => {
231          hilog.error(0x0000, 'testTag', 'sendMessageRequest got exception: ' + e);
232        })
233        .finally(() => {
234          data.reclaim();
235          reply.reclaim();
236        })
237    }
238   ```
239
240### Server Handling of Client Requests
241
242   Call **onConnect()** to return a stub object inherited from [rpc.RemoteObject](../reference/apis-ipc-kit/js-apis-rpc.md#remoteobject), and implement [onRemoteMessageRequest](../reference/apis-ipc-kit/js-apis-rpc.md#onremotemessagerequest9) for the object to process requests sent from the client.
243
244   ```ts
245    import { rpc } from '@kit.IPCKit';
246    import { hilog } from '@kit.PerformanceAnalysisKit';
247
248    class Stub extends rpc.RemoteObject {
249      constructor(descriptor: string) {
250        super(descriptor);
251      }
252      onRemoteMessageRequest(code: number, data: rpc.MessageSequence, reply: rpc.MessageSequence, option: rpc.MessageOption): boolean | Promise<boolean> {
253        // The server stub executes the corresponding processing based on the request code.
254        if (code == 1) {
255          let str = data.readString();
256          hilog.info(0x0000, 'testTag', 'stub receive str : ' + str);
257          // The server sends the request processing result to the client.
258          reply.writeString("hello rpc");
259          return true;
260        } else {
261            hilog.info(0x0000, 'testTag', 'stub unknown code: ' + code);
262            return false;
263        }
264      }
265    }
266   ```
267
268### Terminating the Connection
269
270   After IPC is complete, the FA model calls [disconnectAbility](../reference/apis-ability-kit/js-apis-ability-featureAbility.md#featureabilitydisconnectability7) to disable the connection. The **connectId** is saved when the service is connected.
271
272  <!--code_no_check_fa-->
273  ```ts
274    import { featureAbility } from "@kit.AbilityKit";
275    import { hilog } from '@kit.PerformanceAnalysisKit';
276
277    function disconnectCallback() {
278      hilog.info(0x0000, 'testTag', 'disconnect ability done');
279    }
280    // Use the connectId saved when the service is successfully connected to disable the connection.
281    featureAbility.disconnectAbility(connectId, disconnectCallback);
282   ```
283
284   The **common.UIAbilityContext** provides the [disconnectServiceExtensionAbility](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#disconnectserviceextensionability-1) API to disconnect from the service. The **connectId** is saved when the service is connected.
285   In the sample code provided in this topic, **this.getUIContext().getHostContext()** is used to obtain **UIAbilityContext**, where **this** indicates a UIAbility instance inherited from **UIAbility**. To use **UIAbilityContext** APIs on pages, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
286
287  <!--code_no_check-->
288  ```ts
289    let context: common.UIAbilityContext = this.getUIContext().getHostContext(); // UIAbilityContext
290
291    // Use the connectId saved when the service is successfully connected to disable the connection.
292    context.disconnectServiceExtensionAbility(connectId);
293   ```
294
295## Sample
296
297For the end-to-end complete example of IPC and RPC development, see the following:
298
299- [Complete IPC Example - Using Parcelable/ArrayBuffer](https://gitcode.com/openharmony/applications_app_samples/tree/master/code/SystemFeature/IPC/ObjectTransfer)
300