Skip to content

Electron 命令合计

Invoke 异步发送请求

  • html 代码
html
<button @click="invoke" class="pageItem">Invoke发送异步消息</button>
  • js 代码
js
import { ipcApiRoute } from "@/api/main";
import { ipc } from "@/utils/ipcRenderer";
// 方法
invoke() {
  ipc.invoke(ipcApiRoute.invokedemo, {}).then((res) => {
    window.alert(res);
  });
},
  • 控制器
js
  /**
   * invoke
   */
  invoke() {
    const result = Services.get("button").invoke("这就是异步的invoke");
    // 异步请求 我这里没写async await 所以直接返回了异步没等待
    return "异步没等待";
  }
  • 服务层
js
  /**
   * invoke
   */
  async invoke(args) {
    let obj = {
      status: "ok",
      params: args,
    };
    return obj;
  }

sendSync 发送同步消息(send/on)模型

  • html 代码
html
<button @click="sendSync" class="pageItem">
  sendSync发送同步消息(send/on)模型
</button>
  • js 代码
js
  /**
   * @description: 同步消息
   * @return {*}
   */
  sendSync() {
    // 发送了同步消息
    // 阻塞进程 没有收到消息 页面卡死 弹窗不提示
    const result = ipc.sendSync(ipcApiRoute.sendSync, "同步");
    if (result) {
      window.alert("同步消息 否则卡死了");
    }
  },
  • 控制器
js
  /*
   * 同步请求
   */
  sendSync() {
    const data = "测试同步";
    setTimeout(() => {
      return data;
    }, 100000);
  }

长监听

  • html 代码
html
<button @click="onlistener(1)" class="pageItem">
  监听 channel, 当新消息到达,调用 on 监听
</button>
  • js 代码
js
import { ipcApiRoute } from "@/api/main";
import { ipc } from "@/utils/ipcRenderer";

mounted() {
  // 长监听
  this.init();
},

/**
 * @description: 监听后的回调函数
 * @param {*} event 事件
 * @param {*} result 结果
 * @return {*}
 */
callback(event, result) {
  // 监听结果
  console.log(event);
  console.log("********");
  console.log(result);
},

/**
 * @description: 长连接监听
 * @return {*}
 */
init() {
  // 监听
  ipc.removeListener(ipcApiRoute.newsender, this.callback);
  ipc.on(ipcApiRoute.newsender, this.callback);
},

/**
 * @description: 开启长监听
 * @return {*}
 */
  async onlistener(args, event) {
    const { type, content, id } = args;
    const data = await Services.get("button").sendlongmessage(
      type,
      content,
      event,
      id
    );
    return data;
  }
  • 控制器
js
/*监听请求
  */
async onlistener(args, event) {
    const { type, content, id } = args;
    const data = await Services.get("button").sendlongmessage(
      type,
      content,
      event,
      id
    );
    return data;
  }
  • 服务层
js
class ButtonService extends Service {
  myTimer = new Map();
  constructor(ctx) {
    super(ctx);
  }
  /* 监听长消息 */
  sendlongmessage(type, content, event, id) {
    // 前端ipc频道 channel,不要和前端发送的控制器重名
    const channel = "controller.button.newsender";
    if (type == "start") {
      // 判断有没有 定时器
      if (this.myTimer.has(id)) {
        return "已经开始了";
      }
      // 执行代码
      let result = this.sendlongcontent(content, event, id, channel);
      // ! 存储到Map
      this.myTimer.set(id, result);
      return "开始了";
    } else if (type == "end") {
      if (this.myTimer.has(id)) {
        // !清除定时器
        clearInterval(this.myTimer.get(id));
        // !删除指定的map键值对
        this.myTimer.delete(id);
        // !打印map的个数看删除成功没有
        console.log(this.myTimer.size);
      }
      return "停止了";
    } else {
      return "ohther";
    }
  }
  sendlongcontent(content, event, id, channel) {
    // !开启定时器
    let result = setInterval(() => {
      let timeNow = Date.now();
      let data = `这是第${id}个数据:` + content + ":" + timeNow;
      console.log("12345" + data);
      event.reply(`${channel}`, data); // 第一个参数 频道 第二个参数 数据
    }, 1000);
    return result;
  }
}

停止监听

  • html 代码
js
<button @click="stopListener(1)" class="pageItem">停止监听</button>
  • js 代码
js
/**
 * @description: 手动关闭长监听
 * @return {*}
 */
stopListener(id) {
  const params = {
    type: "end",
    content: "",
    id,
  };
  ipc.send(ipcApiRoute.onlistener, params);
},
  • 控制器
js
/*
一次性监听
*/
async oncelistener(args, event) {
  const { type, content } = args;
  return content;
}
  • 服务层

因为会有多个定时器,所以这里用了 Map

js
class ButtonService extends Service {
  myTimer = new Map();
  constructor(ctx) {
    super(ctx);
  }
  /* 监听长消息 */
  sendlongmessage(type, content, event, id) {
    // 前端ipc频道 channel
    const channel = "controller.button.onlistener";
    if (type == "start") {
      // 判断有没有 定时器
      if (this.myTimer.has(id)) {
        return "已经开始了";
      }
      // 执行代码
      let result = this.sendlongcontent(content, event, id, channel);
      // ! 存储到Map
      this.myTimer.set(id, result);
      return "开始了";
    } else if (type == "end") {
      if (this.myTimer.has(id)) {
        // !清除定时器
        clearInterval(this.myTimer.get(id));
        // !删除指定的map键值对
        this.myTimer.delete(id);
        // !打印map的个数看删除成功没有
        console.log(this.myTimer.size);
      }
      return "停止了";
    } else {
      return "ohther";
    }
  }
  sendlongcontent(content, event, id, channel) {
    // !开启定时器
    let result = setInterval(() => {
      let timeNow = Date.now();
      let data = `这是第${id}个数据:` + content + ":" + timeNow;
      console.log("12345" + data);
      event.reply(`${channel}`, data); // 第一个参数 频道 第二个参数 数据
    }, 1000);
    return result;
  }
}

添加一次性监听(once)

  • html 代码
js
<button @click="oncelistener" class="pageItem">
  添加一次性 listener 函数(once)
</button>
  • js 代码
js
import { ipcApiRoute } from "@/api/main";
import { ipc } from "@/utils/ipcRenderer";

mounted(){
  this.initonce();
}

/**
 * @description: 只监听一次
 * @return {*}
 */

initonce() {
  ipc.once(ipcApiRoute.oncelistener, this.callback);
},
/**
 * @description: 监听后的回调函数
 * @param {*} event 事件
 * @param {*} result 结果
 * @return {*}
 */
callback(event, result) {
  // 监听结果
  console.log(event);
  console.log("********");
  console.log(result);
},

oncelistener() {
  const params = {
    type: "start",
    content: "开始",
  };
  ipc.send(ipcApiRoute.oncelistener, params);
  ipc.send(ipcApiRoute.oncelistener, "第二次消息");
},
  • 控制器
js
/*
一次性监听
*/
async oncelistener(args, event) {
  const { type, content } = args;
  return content;
}

移除监听的函数

removeListener

  • html 代码
html
<button @click="removeListener" class="pageItem">
  为特定的 channel 从监听队列中删除特定的 listener 监听者(removeListener)
</button>
  • js 代码
js
/**
 * @description: 移除onlistener 监听者
 * @return {*}
 */
removeListener() {
  console.log("点击了移除了,移除的是回调事件");
  ipc.removeListener(ipcApiRoute.onlistener, this.callback);
},

移除所有监听者

removeAllListeners

  • html 代码
html
<button @click="removeAllListeners" class="pageItem">
  移除所有的监听器,(removeAllListeners)
</button>
  • js 代码
js
/**
 * @description: 移除所有的监听器
 * @return {*}
 */
removeAllListeners() {
  console.log("点解了移除,移除的是所有监听事件");
  ipc.removeAllListeners();
},

send 不需要接受返回值

  • html 代码
html
<button @click="send" class="pageItem">
  send用法向主进程发送异步消息(send 不需要返回值)
</button>
  • js 代码
js
/**
 * @description: send发送消息不需要返回值。也接收不到返回。一般用于发送通知,不用等待的情况
 * @return {*}
 */
send() {
  ipc.send(ipcApiRoute.senddemo, "1234");
},
  • 控制器
js
  /*******
   * @description: send
   * @param {*} params
   * @return {*}
   */
  async senddemo(params) {
    console.log(params);
    // 你这里写了return 前端也收不到返回值
    return params;
  }

最后汇总

控制器所有代码

js
/**
 * @Author: jsopy
 * @Date: 2024-09-09 10:12:31
 * @LastEditTime: 2024-09-10 11:32:04
 * @FilePath: /demo1/electron/controller/button.js
 * @Description:
 * @
 */

"use strict";

const { Controller } = require("ee-core");
const Log = require("ee-core/log");
const Services = require("ee-core/services");

/**
 * example
 * @class
 */
class ButtonController extends Controller {
  constructor(ctx) {
    super(ctx);
  }
  /**
   * invoke
   */
  invoke() {
    const result = Services.get("button").invoke("这就是异步的invoke");
    // 异步请求 我这里没写async await 所以直接返回了我自定义的数据
    return "异步没等待";
  }
  /*
   * 同步请求
   */
  sendSync() {
    const data = "测试同步";
    setTimeout(() => {
      return data;
    }, 100000);
  }
  /*监听请求
   */
  async onlistener(args, event) {
    const { type, content, id } = args;
    const data = await Services.get("button").sendlongmessage(
      type,
      content,
      event,
      id
    );
    return data;
  }
  /*
  一次性监听
  */
  async oncelistener(args, event) {
    const { type, content } = args;
    return content;
  }

  /*******
   * @description: send
   * @param {*} params
   * @return {*}
   */
  async senddemo(params) {
    console.log(params);
    // 你这里写了return 前端也收不到返回值
    return params;
  }
}

ButtonController.toString = () => "[class ButtonController]";
module.exports = ButtonController;

服务层代码

js
"use strict";

const { Service } = require("ee-core");

/**
 * 示例服务(service层为单例)
 * @class
 */
class ButtonService extends Service {
  myTimer = new Map();
  constructor(ctx) {
    super(ctx);
  }

  /**
   * invoke
   */
  async invoke(args) {
    let obj = {
      status: "ok",
      params: args,
    };

    return obj;
  }
  /* 监听长消息 */
  sendlongmessage(type, content, event, id) {
    // 前端ipc频道 channel
    const channel = "controller.button.newsender";
    if (type == "start") {
      // 判断有没有 定时器
      if (this.myTimer.has(id)) {
        return "已经开始了";
      }
      // 执行代码
      let result = this.sendlongcontent(content, event, id, channel);
      // ! 存储到Map
      this.myTimer.set(id, result);
      return "开始了";
    } else if (type == "end") {
      if (this.myTimer.has(id)) {
        // !清除定时器
        clearInterval(this.myTimer.get(id));
        // !删除指定的map键值对
        this.myTimer.delete(id);
        // !打印map的个数看删除成功没有
        console.log(this.myTimer.size);
      }
      return "停止了";
    } else {
      return "ohther";
    }
  }
  sendlongcontent(content, event, id, channel) {
    // !开启定时器
    let result = setInterval(() => {
      let timeNow = Date.now();
      let data = `这是第${id}个数据:` + content + ":" + timeNow;
      console.log("12345" + data);
      event.reply(`${channel}`, data); // 第一个参数 频道 第二个参数 数据
    }, 1000);
    return result;
  }
}
ButtonService.toString = () => "[class ButtonService]";
module.exports = ButtonService;