ipc-rpc-development-guideline.md 13.5 KB
Newer Older
Z
zengyawen 已提交
1
# IPC与RPC通信开发指导
M
mamingshuai 已提交
2

Z
zengyawen 已提交
3
## 场景介绍
M
mamingshuai 已提交
4 5 6 7

IPC/RPC的主要工作是让运行在不同进程的Proxy和Stub互相通信,包括Proxy和Stub运行在不同设备的情况。


Z
zengyawen 已提交
8
## 接口说明
M
mamingshuai 已提交
9

Z
zengyawen 已提交
10
**表1** Native侧IPC接口
M
mamingshuai 已提交
11

12
| 类/接口 | 方法 | 功能说明 |
Z
zengyawen 已提交
13
| -------- | -------- | -------- |
W
wangqilong2 已提交
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的请求并返回结果。 |
W
wangqilong2 已提交
16
| IRemoteProxy |  | 业务的Pory类需要从IRemoteProxy类派生。 |
M
mamingshuai 已提交
17 18


Z
zengyawen 已提交
19
## 开发步骤
M
mamingshuai 已提交
20

W
wangqilong2 已提交
21
### **Native侧开发步骤**
M
mamingshuai 已提交
22

W
wangqilong2 已提交
23
1. 添加依赖
24

W
wangqilong2 已提交
25
   SDK依赖:
26

W
wangqilong2 已提交
27 28 29 30 31
   ```
   #ipc场景
   external_deps = [
     "ipc:ipc_single",
   ]
32

W
wangqilong2 已提交
33 34 35 36 37
   #rpc场景
   external_deps = [
     "ipc:ipc_core",
   ]
   ```
38

W
wangqilong2 已提交
39
   此外, IPC/RPC依赖的refbase实现在公共基础库下,请增加对utils的依赖:
40

W
wangqilong2 已提交
41 42 43 44 45
   ```
   external_deps = [
     "c_utils:utils",
   ]
   ```
46 47

2. 定义IPC接口ITestAbility
48

Z
zengyawen 已提交
49 50
   SA接口继承IPC基类接口IRemoteBroker,接口里定义描述符、业务函数和消息码,其中业务函数在Proxy端和Stub端都需要实现。

W
wangqilong2 已提交
51 52
   ```c++
   #include "iremote_broker.h"
53

W
wangqilong2 已提交
54
   //定义消息码
55 56
   const int TRANS_ID_PING_ABILITY = 5;

W
wangqilong2 已提交
57
   const std::string DESCRIPTOR = "test.ITestAbility";
58

Z
zengyawen 已提交
59 60
   class ITestAbility : public IRemoteBroker {
   public:
61
       // DECLARE_INTERFACE_DESCRIPTOR是必需的,入参需使用std::u16string;
W
wangqilong2 已提交
62
       DECLARE_INTERFACE_DESCRIPTOR(to_utf16(DESCRIPTOR));
63
       virtual int TestPingAbility(const std::u16string &dummy) = 0; // 定义业务函数
Z
zengyawen 已提交
64 65 66
   };
   ```

67
3. 定义和实现服务端TestAbilityStub
68

Z
zengyawen 已提交
69 70
   该类是和IPC框架相关的实现,需要继承 IRemoteStub<ITestAbility>。Stub端作为接收请求的一端,需重写OnRemoteRequest方法用于接收客户端调用。

W
wangqilong2 已提交
71 72 73
   ```c++
   #include "iability_test.h"
   #include "iremote_stub.h"
74

Z
zengyawen 已提交
75
   class TestAbilityStub : public IRemoteStub<ITestAbility> {
76
   public:
Z
zengyawen 已提交
77 78
       virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
       int TestPingAbility(const std::u16string &dummy) override;
M
mamingshuai 已提交
79
    };
80

81
   int TestAbilityStub::OnRemoteRequest(uint32_t code,
Z
zengyawen 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
       MessageParcel &data, MessageParcel &reply, MessageOption &option)
   {
       switch (code) {
           case TRANS_ID_PING_ABILITY: {
               std::u16string dummy = data.ReadString16();
               int result = TestPingAbility(dummy);
               reply.WriteInt32(result);
               return 0;
           }
           default:
               return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
       }
   }
   ```

97
4. 定义服务端业务函数具体实现类TestAbility
W
wangqilong2 已提交
98 99 100

   ```c++
   #include "iability_server_test.h"
101

Z
zengyawen 已提交
102 103 104 105
   class TestAbility : public TestAbilityStub {
   public:
       int TestPingAbility(const std::u16string &dummy);
   }
106

Z
zengyawen 已提交
107 108 109 110 111
   int TestAbility::TestPingAbility(const std::u16string &dummy) {
       return 0;
   }
   ```

112
5. 定义和实现客户端 TestAbilityProxy
113

Z
zengyawen 已提交
114 115
   该类是Proxy端实现,继承IRemoteProxy&lt;ITestAbility&gt;,调用SendRequest接口向Stub端发送请求,对外暴露服务端提供的能力。

W
wangqilong2 已提交
116 117 118 119
   ```c++
   #include "iability_test.h"
   #include "iremote_proxy.h"
   #include "iremote_object.h"
120

Z
zengyawen 已提交
121 122 123
   class TestAbilityProxy : public IRemoteProxy<ITestAbility> {
   public:
       explicit TestAbilityProxy(const sptr<IRemoteObject> &impl);
W
wangqilong2 已提交
124
       int TestPingAbility(const std::u16string &dummy) override;
Z
zengyawen 已提交
125 126 127
   private:
       static inline BrokerDelegator<TestAbilityProxy> delegator_; // 方便后续使用iface_cast宏
   }
128

Z
zengyawen 已提交
129 130 131 132
   TestAbilityProxy::TestAbilityProxy(const sptr<IRemoteObject> &impl)
       : IRemoteProxy<ITestAbility>(impl)
   {
   }
133

W
wangqilong2 已提交
134
   int TestAbilityProxy::TestPingAbility(const std::u16string &dummy){
Z
zengyawen 已提交
135 136 137 138 139 140
       MessageOption option;
       MessageParcel dataParcel, replyParcel;
       dataParcel.WriteString16(dummy);
       int error = Remote()->SendRequest(TRANS_ID_PING_ABILITY, dataParcel, replyParcel, option);
       int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1;
       return result;
W
wangqilong2 已提交
141
   }
Z
zengyawen 已提交
142
   ```
W
wangqilong2 已提交
143

144
6. SA注册与启动
145 146

   SA需要将自己的TestAbilityStub实例通过AddSystemAbility接口注册到SystemAbilityManager,设备内与分布式的注册参数不同。
Z
zengyawen 已提交
147

W
wangqilong2 已提交
148
   ```c++
Z
zengyawen 已提交
149 150
   // 注册到本设备内
   auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
E
Eight_J 已提交
151
   samgr->AddSystemAbility(saId, new TestAbility());
152

Z
zengyawen 已提交
153 154 155 156
   // 在组网场景下,会被同步到其他设备上
   auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
   ISystemAbilityManager::SAExtraProp saExtra;
   saExtra.isDistributed = true; // 设置为分布式SA
E
Eight_J 已提交
157
   int result = samgr->AddSystemAbility(saId, new TestAbility(), saExtra);
Z
zengyawen 已提交
158 159
   ```

160
7. SA获取与调用
161

Z
zengyawen 已提交
162 163
   通过SystemAbilityManager的GetSystemAbility方法可获取到对应SA的代理IRemoteObject,然后构造TestAbilityProxy即可。

W
wangqilong2 已提交
164
   ```c++
Z
zengyawen 已提交
165 166
   // 获取本设备内注册的SA的proxy
   sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
E
Eight_J 已提交
167
   sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(saId);
Z
zengyawen 已提交
168
   sptr<ITestAbility> testAbility = iface_cast<ITestAbility>(remoteObject); // 使用iface_cast宏转换成具体类型
L
l30043718 已提交
169
   
170
   // 获取其他设备注册的SA的proxy
Z
zengyawen 已提交
171
   sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
L
l30043718 已提交
172
   
W
wangqilong2 已提交
173 174
   // networkId是组网场景下对应设备的标识符,可以通过GetLocalNodeDeviceInfo获取
   sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(saId, networkId);
Z
zengyawen 已提交
175 176
   sptr<TestAbilityProxy> proxy(new TestAbilityProxy(remoteObject)); // 直接构造具体Proxy
   ```
Z
zengyawen 已提交
177

W
wangqilong2 已提交
178
### **JS侧开发步骤**
179 180 181

1. 添加依赖

W
wangqilong2 已提交
182
   ```ts
L
l30043718 已提交
183
   import rpc from '@ohos.rpc';
184 185
   // 仅FA模型需要导入@ohos.ability.featureAbility
   // import featureAbility from "@ohos.ability.featureAbility";
W
wangqilong2 已提交
186 187
   ```

188 189 190
   Stage模型需要获取context

   ```ts
L
l30043718 已提交
191 192 193 194
   import UIAbility from '@ohos.app.ability.UIAbility';
   import Want from '@ohos.app.ability.Want';
   import AbilityConstant from '@ohos.app.ability.AbilityConstant';
   import window from '@ohos.window';
195

L
l30043718 已提交
196 197
   export default class MainAbility extends UIAbility {
       onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
198
           console.log("[Demo] MainAbility onCreate");
L
l30043718 已提交
199
           let context = this.context;
200 201 202 203
       }
       onDestroy() {
           console.log("[Demo] MainAbility onDestroy");
       }
L
l30043718 已提交
204
       onWindowStageCreate(windowStage: window.WindowStage) {
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
           // Main window is created, set main page for this ability
           console.log("[Demo] MainAbility onWindowStageCreate");
       }
       onWindowStageDestroy() {
           // Main window is destroyed, release UI related resources
           console.log("[Demo] MainAbility onWindowStageDestroy");
       }
       onForeground() {
           // Ability has brought to foreground
           console.log("[Demo] MainAbility onForeground");
       }
       onBackground() {
           // Ability has back to background
           console.log("[Demo] MainAbility onBackground");
       }
   }
   ```
222

W
wangqilong2 已提交
223
2. 绑定Ability
224

225
   首先,构造变量want,指定要绑定的Ability所在应用的包名、组件名,如果是跨设备的场景,还需要绑定目标设备NetworkId(组网场景下对应设备的标识符,可以使用deviceManager获取目标设备的NetworkId);然后,构造变量connect,指定绑定成功、绑定失败、断开连接时的回调函数;最后,FA模型使用featureAbility提供的接口绑定Ability,Stage模型通过context获取服务后用提供的接口绑定Ability。
W
wangqilong2 已提交
226 227

   ```ts
228 229
   // 仅FA模型需要导入@ohos.ability.featureAbility
   // import featureAbility from "@ohos.ability.featureAbility";
L
l30043718 已提交
230 231 232 233
   import rpc from '@ohos.rpc';
   import Want from '@ohos.app.ability.Want';
   import common from '@ohos.app.ability.common';
   import deviceManager from '@ohos.distributedHardware.deviceManager';
L
l30043718 已提交
234
   import { BusinessError } from '@ohos.base';
235

L
l30043718 已提交
236 237
   let dmInstance: deviceManager.DeviceManager | undefined;
   let proxy: rpc.IRemoteObject | undefined = undefined;
L
l30043718 已提交
238
   let connectId: number;
239

W
wangqilong2 已提交
240
   // 单个设备绑定Ability
L
l30043718 已提交
241
   let want: Want = {
242
       // 包名和组件名写实际的值
L
l30043718 已提交
243 244
       bundleName: "ohos.rpc.test.server",
       abilityName: "ohos.rpc.test.server.ServiceAbility",
245
   };
L
l30043718 已提交
246
   let connect: common.ConnectOptions = {
L
l30043718 已提交
247
       onConnect: (elementName, remote) => {
248
           proxy = remote;
249
       },
L
l30043718 已提交
250
       onDisconnect: (elementName) => {
251
       },
L
l30043718 已提交
252 253
       onFailed: () => {
           proxy;
254
       }
255 256 257 258
   };
   // FA模型使用此方法连接服务
   // connectId = featureAbility.connectAbility(want, connect);

L
l30043718 已提交
259
   connectId = this.context.connectServiceExtensionAbility(want,connect);
260

L
l30043718 已提交
261 262 263
   // 跨设备绑定 
   let deviceManagerCallback = (err: BusinessError, data: deviceManager.DeviceManager) => {
       if (err) {
L
l30043718 已提交
264 265
           console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
           return;
L
l30043718 已提交
266 267
       }
       console.info("createDeviceManager success");
L
l30043718 已提交
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
       dmInstance = data;
   }
   try{
       deviceManager.createDeviceManager("ohos.rpc.test", deviceManagerCallback);
   } catch(error) {
       let e: BusinessError = error as BusinessError;
       console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
   }

   // 使用deviceManager获取目标设备NetworkId
   if (dmInstance != undefined) {
       let deviceList: Array<deviceManager.DeviceInfo> = dmInstance.getTrustedDeviceListSync();
       let networkId: string = deviceList[0].networkId;
       let want: Want = {
           bundleName: "ohos.rpc.test.server",
           abilityName: "ohos.rpc.test.service.ServiceAbility",
           deviceId: networkId,
           flags: 256
       };
       // 建立连接后返回的Id需要保存下来,在断开连接时需要作为参数传入
       // FA模型使用此方法连接服务
       // connectId = featureAbility.connectAbility(want, connect);
       
       // 第一个参数是本应用的包名,第二个参数是接收deviceManager的回调函数
       connectId = this.context.connectServiceExtensionAbility(want,connect);
L
l30043718 已提交
293
   }
294 295
   ```

W
wangqilong2 已提交
296
3. 服务端处理客户端请求
297

W
wangqilong2 已提交
298
   服务端被绑定的Ability在onConnect方法里返回继承自rpc.RemoteObject的对象,该对象需要实现onRemoteMessageRequest方法,处理客户端的请求。
299

W
wangqilong2 已提交
300
   ```ts
L
l30043718 已提交
301
    class Stub extends rpc.RemoteObject {
L
l30043718 已提交
302
       constructor(descriptor: string) {
303
           super(descriptor);
304
       }
L
l30043718 已提交
305
       onRemoteMessageRequest(code: number, data: rpc.MessageSequence, reply: rpc.MessageSequence, option: rpc.MessageOption): boolean | Promise<boolean> {
306
           // 根据code处理客户端的请求
307
           return true;
308
       }
L
l30043718 已提交
309 310 311 312 313
    }
    onConnect(want: Want) {
           const robj: rpc.RemoteObject = new Stub("rpcTestAbility");
           return robj;
    } 
314 315
   ```

W
wangqilong2 已提交
316
4. 客户端处理服务端响应
317

318
   客户端在onConnect回调里接收到代理对象,调用sendRequest方法发起请求,在期约(JavaScript期约:用于表示一个异步操作的最终完成或失败及其结果值)或者回调函数里接收结果。
319

W
wangqilong2 已提交
320
   ```ts
L
l30043718 已提交
321
   import rpc from '@ohos.rpc';
322
   // 使用期约
323 324 325
   let option = new rpc.MessageOption();
   let data = rpc.MessageParcel.create();
   let reply = rpc.MessageParcel.create();
326
   // 往data里写入参数
327
   proxy.sendRequest(1, data, reply, option)
L
l30043718 已提交
328
       .then((result: rpc.SendRequestResult) => {
329
           if (result.errCode != 0) {
330 331
               console.error("send request failed, errCode: " + result.errCode);
               return;
332 333 334
           }
           // 从result.reply里读取结果
       })
L
l30043718 已提交
335
       .catch((e: Error) => {
336 337
           console.error("send request got exception: " + e);
       })
338
       .finally(() => {
339 340
           data.reclaim();
           reply.reclaim();
341
       })
342

343
   // 使用回调函数
L
l30043718 已提交
344
   function sendRequestCallback(result: rpc.SendRequestResult) {
345 346
       try {
           if (result.errCode != 0) {
347 348
               console.error("send request failed, errCode: " + result.errCode);
               return;
349 350 351
           }
           // 从result.reply里读取结果
       } finally {
352 353
           result.data.reclaim();
           result.reply.reclaim();
354 355
       }
   }
356 357 358
   let option = new rpc.MessageOption();
   let data = rpc.MessageParcel.create();
   let reply = rpc.MessageParcel.create();
359
   // 往data里写入参数
360
   proxy.sendRequest(1, data, reply, option, sendRequestCallback);
361 362
   ```

W
wangqilong2 已提交
363
5. 断开连接
364

365
   IPC通信结束后,FA模型使用featureAbility的接口断开连接,Stage模型在获取context后用提供的接口断开连接。
366

W
wangqilong2 已提交
367
   ```ts
368 369 370
   import rpc from "@ohos.rpc";
   // 仅FA模型需要导入@ohos.ability.featureAbility
   // import featureAbility from "@ohos.ability.featureAbility";
L
l30043718 已提交
371

372
   function disconnectCallback() {
373
       console.info("disconnect ability done");
374
   }
375 376 377
   // FA模型使用此方法断开连接
   // featureAbility.disconnectAbility(connectId, disconnectCallback);

L
l30043718 已提交
378
   this.context.disconnectServiceExtensionAbility(connectId);
379 380
   ```

381 382 383 384 385
## 相关实例

针对IPC与RPC通信开发,有以下相关实例可供参考:

- [RPC通信(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/RPC)