• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# IPC与RPC通信开发指导
2
3## 场景介绍
4
5IPC/RPC的主要工作是让运行在不同进程的Proxy和Stub互相通信,包括Proxy和Stub运行在不同设备的情况。
6
7
8## 接口说明
9
10**表1** Native侧IPC接口
11
12| 类/接口 | 方法 | 功能说明 |
13| -------- | -------- | -------- |
14| [IRemoteBroker](../reference/apis/js-apis-rpc.md#iremotebroker) | sptr<IRemoteObject> AsObject() | 返回通信对象。Stub端返回RemoteObject对象本身,Proxy端返回代理对象。 |
15| IRemoteStub | virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) | 请求处理方法,派生类需要重写该方法用来处理Proxy的请求并返回结果。 |
16| IRemoteProxy |  | 业务的Pory类需要从IRemoteProxy类派生。 |
17
18
19## 开发步骤
20
21### **Native侧开发步骤**
22
231. 添加依赖
24
25   SDK依赖:
26
27   ```
28   #ipc场景
29   external_deps = [
30     "ipc:ipc_single",
31   ]
32
33   #rpc场景
34   external_deps = [
35     "ipc:ipc_core",
36   ]
37   ```
38
39   此外, IPC/RPC依赖的refbase实现在公共基础库下,请增加对utils的依赖:
40
41   ```
42   external_deps = [
43     "c_utils:utils",
44   ]
45   ```
46
472. 定义IPC接口ITestAbility
48
49   SA接口继承IPC基类接口IRemoteBroker,接口里定义描述符、业务函数和消息码,其中业务函数在Proxy端和Stub端都需要实现。
50
51   ```c++
52   #include "iremote_broker.h"
53
54   //定义消息码
55   const int TRANS_ID_PING_ABILITY = 5;
56
57   const std::string DESCRIPTOR = "test.ITestAbility";
58
59   class ITestAbility : public IRemoteBroker {
60   public:
61       // DECLARE_INTERFACE_DESCRIPTOR是必需的,入参需使用std::u16string;
62       DECLARE_INTERFACE_DESCRIPTOR(to_utf16(DESCRIPTOR));
63       virtual int TestPingAbility(const std::u16string &dummy) = 0; // 定义业务函数
64   };
65   ```
66
673. 定义和实现服务端TestAbilityStub
68
69   该类是和IPC框架相关的实现,需要继承 IRemoteStub<ITestAbility>。Stub端作为接收请求的一端,需重写OnRemoteRequest方法用于接收客户端调用。
70
71   ```c++
72   #include "iability_test.h"
73   #include "iremote_stub.h"
74
75   class TestAbilityStub : public IRemoteStub<ITestAbility> {
76   public:
77       virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
78       int TestPingAbility(const std::u16string &dummy) override;
79    };
80
81   int TestAbilityStub::OnRemoteRequest(uint32_t code,
82       MessageParcel &data, MessageParcel &reply, MessageOption &option)
83   {
84       switch (code) {
85           case TRANS_ID_PING_ABILITY: {
86               std::u16string dummy = data.ReadString16();
87               int result = TestPingAbility(dummy);
88               reply.WriteInt32(result);
89               return 0;
90           }
91           default:
92               return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
93       }
94   }
95   ```
96
974. 定义服务端业务函数具体实现类TestAbility
98
99   ```c++
100   #include "iability_server_test.h"
101
102   class TestAbility : public TestAbilityStub {
103   public:
104       int TestPingAbility(const std::u16string &dummy);
105   }
106
107   int TestAbility::TestPingAbility(const std::u16string &dummy) {
108       return 0;
109   }
110   ```
111
1125. 定义和实现客户端 TestAbilityProxy
113
114   该类是Proxy端实现,继承IRemoteProxy&lt;ITestAbility&gt;,调用SendRequest接口向Stub端发送请求,对外暴露服务端提供的能力。
115
116   ```c++
117   #include "iability_test.h"
118   #include "iremote_proxy.h"
119   #include "iremote_object.h"
120
121   class TestAbilityProxy : public IRemoteProxy<ITestAbility> {
122   public:
123       explicit TestAbilityProxy(const sptr<IRemoteObject> &impl);
124       int TestPingAbility(const std::u16string &dummy) override;
125   private:
126       static inline BrokerDelegator<TestAbilityProxy> delegator_; // 方便后续使用iface_cast宏
127   }
128
129   TestAbilityProxy::TestAbilityProxy(const sptr<IRemoteObject> &impl)
130       : IRemoteProxy<ITestAbility>(impl)
131   {
132   }
133
134   int TestAbilityProxy::TestPingAbility(const std::u16string &dummy){
135       MessageOption option;
136       MessageParcel dataParcel, replyParcel;
137       dataParcel.WriteString16(dummy);
138       int error = Remote()->SendRequest(TRANS_ID_PING_ABILITY, dataParcel, replyParcel, option);
139       int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1;
140       return result;
141   }
142   ```
143
1446. SA注册与启动
145
146   SA需要将自己的TestAbilityStub实例通过AddSystemAbility接口注册到SystemAbilityManager,设备内与分布式的注册参数不同。
147
148   ```c++
149   // 注册到本设备内
150   auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
151   samgr->AddSystemAbility(saId, new TestAbility());
152
153   // 在组网场景下,会被同步到其他设备上
154   auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
155   ISystemAbilityManager::SAExtraProp saExtra;
156   saExtra.isDistributed = true; // 设置为分布式SA
157   int result = samgr->AddSystemAbility(saId, new TestAbility(), saExtra);
158   ```
159
1607. SA获取与调用
161
162   通过SystemAbilityManager的GetSystemAbility方法可获取到对应SA的代理IRemoteObject,然后构造TestAbilityProxy即可。
163
164   ```c++
165   // 获取本设备内注册的SA的proxy
166   sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
167   sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(saId);
168   sptr<ITestAbility> testAbility = iface_cast<ITestAbility>(remoteObject); // 使用iface_cast宏转换成具体类型
169
170   // 获取其他设备注册的SA的proxy
171   sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
172
173   // networkId是组网场景下对应设备的标识符,可以通过GetLocalNodeDeviceInfo获取
174   sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(saId, networkId);
175   sptr<TestAbilityProxy> proxy(new TestAbilityProxy(remoteObject)); // 直接构造具体Proxy
176   ```
177
178### **JS侧开发步骤**
179
1801. 添加依赖
181
182   ```ts
183   import rpc from "@ohos.rpc";
184   // 仅FA模型需要导入@ohos.ability.featureAbility
185   // import featureAbility from "@ohos.ability.featureAbility";
186   ```
187
188   Stage模型需要获取context
189
190   ```ts
191   import Ability from "@ohos.app.ability.UIAbility";
192
193   export default class MainAbility extends Ability {
194       onCreate(want, launchParam) {
195           console.log("[Demo] MainAbility onCreate");
196           globalThis.context = this.context;
197       }
198       onDestroy() {
199           console.log("[Demo] MainAbility onDestroy");
200       }
201       onWindowStageCreate(windowStage) {
202           // Main window is created, set main page for this ability
203           console.log("[Demo] MainAbility onWindowStageCreate");
204       }
205       onWindowStageDestroy() {
206           // Main window is destroyed, release UI related resources
207           console.log("[Demo] MainAbility onWindowStageDestroy");
208       }
209       onForeground() {
210           // Ability has brought to foreground
211           console.log("[Demo] MainAbility onForeground");
212       }
213       onBackground() {
214           // Ability has back to background
215           console.log("[Demo] MainAbility onBackground");
216       }
217   }
218   ```
219
2202. 绑定Ability
221
222   首先,构造变量want,指定要绑定的Ability所在应用的包名、组件名,如果是跨设备的场景,还需要绑定目标设备NetworkId(组网场景下对应设备的标识符,可以使用deviceManager获取目标设备的NetworkId);然后,构造变量connect,指定绑定成功、绑定失败、断开连接时的回调函数;最后,FA模型使用featureAbility提供的接口绑定Ability,Stage模型通过context获取服务后用提供的接口绑定Ability。
223
224   ```ts
225   import rpc from "@ohos.rpc";
226   // 仅FA模型需要导入@ohos.ability.featureAbility
227   // import featureAbility from "@ohos.ability.featureAbility";
228
229   let proxy = null;
230   let connectId = null;
231
232   // 单个设备绑定Ability
233   let want = {
234       // 包名和组件名写实际的值
235       "bundleName": "ohos.rpc.test.server",
236       "abilityName": "ohos.rpc.test.server.ServiceAbility",
237   };
238   let connect = {
239       onConnect:function(elementName, remote) {
240           proxy = remote;
241       },
242       onDisconnect:function(elementName) {
243       },
244       onFailed:function() {
245           proxy = null;
246       }
247   };
248   // FA模型使用此方法连接服务
249   // connectId = featureAbility.connectAbility(want, connect);
250
251   connectId = globalThis.context.connectServiceExtensionAbility(want,connect);
252
253   // 如果是跨设备绑定,可以使用deviceManager获取目标设备NetworkId
254   import deviceManager from '@ohos.distributedHardware.deviceManager';
255   function deviceManagerCallback(deviceManager) {
256       let deviceList = deviceManager.getTrustedDeviceListSync();
257       let networkId = deviceList[0].networkId;
258       let want = {
259           "bundleName": "ohos.rpc.test.server",
260           "abilityName": "ohos.rpc.test.service.ServiceAbility",
261           "networkId": networkId,
262           "flags": 256
263       };
264       // 建立连接后返回的Id需要保存下来,在断开连接时需要作为参数传入
265       // FA模型使用此方法连接服务
266       // connectId = featureAbility.connectAbility(want, connect);
267
268       connectId = globalThis.context.connectServiceExtensionAbility(want,connect);
269   }
270   // 第一个参数是本应用的包名,第二个参数是接收deviceManager的回调函数
271   deviceManager.createDeviceManager("ohos.rpc.test", deviceManagerCallback);
272   ```
273
274
2753. 服务端处理客户端请求
276
277   服务端被绑定的Ability在onConnect方法里返回继承自rpc.RemoteObject的对象,该对象需要实现onRemoteMessageRequest方法,处理客户端的请求。
278
279   ```ts
280   onConnect(want: Want) {
281       var robj:rpc.RemoteObject = new Stub("rpcTestAbility");
282       return robj;
283   }
284   class Stub extends rpc.RemoteObject {
285       constructor(descriptor) {
286           super(descriptor);
287       }
288       onRemoteMessageRequest(code, data, reply, option) {
289           // 根据code处理客户端的请求
290           return true;
291       }
292   }
293   ```
294
2954. 客户端处理服务端响应
296
297   客户端在onConnect回调里接收到代理对象,调用sendRequest方法发起请求,在期约(JavaScript期约:用于表示一个异步操作的最终完成或失败及其结果值)或者回调函数里接收结果。
298
299   ```ts
300   // 使用期约
301   let option = new rpc.MessageOption();
302   let data = rpc.MessageParcel.create();
303   let reply = rpc.MessageParcel.create();
304   // 往data里写入参数
305   proxy.sendRequest(1, data, reply, option)
306       .then(function(result) {
307           if (result.errCode != 0) {
308               console.error("send request failed, errCode: " + result.errCode);
309               return;
310           }
311           // 从result.reply里读取结果
312       })
313       .catch(function(e) {
314           console.error("send request got exception: " + e);
315       })
316       .finally(() => {
317           data.reclaim();
318           reply.reclaim();
319       })
320
321   // 使用回调函数
322   function sendRequestCallback(result) {
323       try {
324           if (result.errCode != 0) {
325               console.error("send request failed, errCode: " + result.errCode);
326               return;
327           }
328           // 从result.reply里读取结果
329       } finally {
330           result.data.reclaim();
331           result.reply.reclaim();
332       }
333   }
334   let option = new rpc.MessageOption();
335   let data = rpc.MessageParcel.create();
336   let reply = rpc.MessageParcel.create();
337   // 往data里写入参数
338   proxy.sendRequest(1, data, reply, option, sendRequestCallback);
339   ```
340
3415. 断开连接
342
343   IPC通信结束后,FA模型使用featureAbility的接口断开连接,Stage模型在获取context后用提供的接口断开连接。
344
345   ```ts
346   import rpc from "@ohos.rpc";
347   // 仅FA模型需要导入@ohos.ability.featureAbility
348   // import featureAbility from "@ohos.ability.featureAbility";
349   function disconnectCallback() {
350       console.info("disconnect ability done");
351   }
352   // FA模型使用此方法断开连接
353   // featureAbility.disconnectAbility(connectId, disconnectCallback);
354
355   globalThis.context.disconnectServiceExtensionAbility(connectId);
356   ```
357
358