IPC API
安装
npm install @cutos/core
引入依赖
import {CoreAPI} from '@cutos/core';
CoreAPI.getIPC
获取IPC实例对象
let ipc = CoreAPI.getIPC([destAddress]);
- destAddress: 可选参数,目标IP地址,用于设备间进程通信
ipc.sendTo
发送IPC信息
ipc.sendTo(channel, args, callback = null);
- channel: 频道名称
- args: 发送的信息
- callback: 回调函数
ipc.on
监听IPC
ipc.on(channel, listener);
- channel: 频道名称
- listener: 监听函数 (args, respond)
本地设备通信举例:
举例1(不含返回值):
import {CoreAPI} from '@cutos/core';
CoreAPI.init();
let channel1 = 'channel1';
let ipc = CoreAPI.getIPC();
//监听IPC信息
ipc.on(channel1, (args) => {
console.log('on', channel1, 'received', args);
})
//发送IPC信息
ipc.sendTo(channel1, 'no callback');
- 返回结果示例:
on channel1 received: "no callback"
举例2(含返回值):
import {CoreAPI} from '@cutos/core';
CoreAPI.init();
let channel2 = 'channel2';
let ipc = CoreAPI.getIPC();
//监听IPC信息
ipc.on(channel2, (args, respond) => {
console.log('on ' + channel2 + ' received: ' + JSON.stringify(args));
respond({sum: args.opt1 + args.opt2})
})
//发送IPC信息
ipc.sendTo(channel2, {opt1: 2, opt2: 2}, (result) => {
console.log('on ' + channel2 + ' callback: ' + JSON.stringify(result))
});
- 返回结果示例:
on channel2 received: {"opt1":2,"opt2":2}
on channel2 callback: {"sum":4}
设备间进程通信举例:
发送方(IP:192.168.1.136)
import {CoreAPI} from '@cutos/core';
CoreAPI.init();
let channel1 = 'channel1';
//目标IP:192.168.1.149
let ipc = CoreAPI.getIPC("192.168.1.149");
//发送IPC信息
ipc.sendTo(channel1, 'no callback');
接收方(IP:192.168.1.149)
import {CoreAPI} from '@cutos/core';
CoreAPI.init();
let channel1 = 'channel1';
let ipc = CoreAPI.getIPC();
//监听IPC信息
let ipcListener = function (args) {
console.log('on', channel1, 'received', args);
}
ipc.on(channel1, ipcListener);
- 返回结果示例:
on channel1 received: "no callback"