Skip to content

通信介绍

前端和业务通过三种方式通信,可依据需求搭配使用

  • ipc

  • http/https

  • socket

IPC

  • 优点: 双向通信

  • 文件: 前端引入 ipcRenderer

单向通信

bash

# 定义通信频道,即路由
const ipcApiRoute = {
  hello: 'controller.example.hello',
}

# 发送请求
# 该请求会访问 controller/example.js文件的hello函数
import { ipc } from '@/utils/ipcRenderer';

ipc.invoke(ipcApiRoute.hello, {name:'张三'}).then(r => {
	// r为返回的数据
  conson.log(r);
})

双向通信

bash

# 定义通信频道,即路由
const ipcApiRoute = {
  ipcSendMsg: 'controller.example.ipcSendMsg',
}

// 避免重复监听,或者将 $ipc.on() 功能写到一个统一的地方,只加载一次
ipc.removeAllListeners(ipcApiRoute.ipcSendMsg);

// 监听,接收 服务端 event.reply()发送的数据
ipc.on(ipcApiRoute.ipcSendMsg, (event, result) => {
    console.log('[ipcRenderer] [ipcSendMsg] result:', result);

    self.messageString = result;
    // 调用后端的另一个接口
    event.sender.send(ipcApiRoute.hello, 'electron-egg');
})

// 发送请求到服务端
ipc.send(ipcApiRoute.ipcSendMsg, '参数')

预加载模块通信

bash

# 向前端发消息
// 频道
const channel = 'controller.example.ipcSendMsg';
// 使用主窗口的 webContents.send() 方法
eeApp.mainWindow.webContents.send(channel, {name:'张三'});

ipc 通信文档

ipcRenderer

HTTP/HTTPS(一般用 axios)

优点:可在前端、浏览器、终端命令(curl)等,跨界访问 EE 程序

打开配置文件

bash

/* 内置http服务 */
config.httpServer = {
  enable: false, // 是否启用
  https: {
    enable: false,
    key: '/public/ssl/localhost+1.key', // key文件
    cert: '/public/ssl/localhost+1.pem' // cert文件
  },
  port: 7071, // 默认端口(如果端口被使用,则随机获取一个)
  cors: {
    origin: "*" // 跨域
  },
  body: {
    multipart: true,
    formidable: {
      keepExtensions: true
    }
  }
};

cors 属性

  • origin 配置 Access-Control-Allow-Origin CORS header,字符串 或 函数, 它将 ctx 作为第一个参数

  • exposeHeaders 配置 Access-Control-Expose-Headers CORS header,类型:Array

  • maxAge 配置 Access-Control-Max-Age CORS header,类型:Number

  • credentials 配置 Access-Control-Allow-Credentials CORS header. 类型:Boolean.

  • allowMethods 配置 Access-Control-Allow-Methods CORS header. 类型:array ,默认值 ['GET', 'PUT', 'POST', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']

  • allowHeaders 配置 Access-Control-Allow-Headers CORS header. 类型:Array

bash
{
  origin: function(ctx) {
    if (ctx.url === '/test') {
      return false;
    }
    return '*';
  },
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  maxAge: 5,
  credentials: true,
  allowMethods: ['GET', 'POST', 'DELETE'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}

body 属性

  • patchNode {Boolean} 将请求 body 修补到 Node's ctx.req,默认值:false

  • patchKoa {Boolean} 将请求 body 修补到 Koa's ctx.request, 默认值:true

  • jsonLimit {String|Integer} JSON body 大小限制,默认值:1mb

  • formLimit {String|Integer} form body 大小限制,默认值:56kb

  • textLimit {String|Integer} text body 大小限制,默认值:56kb

  • encoding {String} 设置传入表单字段的编码,默认值:utf-8

  • multipart {Boolean} 解析 multipart bodies,默认值:false

  • urlencoded {Boolean} 解析 urlencoded bodies,默认值:true

  • text {Boolean} 解析 text bodies,比如 XML,默认值:true

  • json {Boolean} 解析 JSON bodies,默认值:true

  • jsonStrict {Boolean} 切换 co-body 严格模式;如果设为 true - 仅仅解析 arrays 或 objects,默认值:true

  • includeUnparsed {Boolean} 切换 co-body returnRawBody 选项; 如果设为 true, 对于表单编码和 JSON 请求原始,未解析的 body 使用 Symbol 被连接到 ctx.request.body,默认值:false

  • formidable {Object} 见下方

  • onError {Function} 自定义错误句柄,如果抛出错误,可以自定义响应 - onError(error, context), 默认值将抛出

  • strict {Boolean} DEPRECATED If enabled, 不解析 GET, HEAD, DELETE 请求,默认值:true

  • parsedMethods {String[]} 声明将在其中解析实体的 HTTP 方法,默认值:['POST', 'PUT', 'PATCH']. 替换 strict 选项关于

关于 formidable 对象

  • maxFields {Integer} 限制 querystring 解析器将解码的字段数,默认值:1000

  • maxFieldsSize {Integer} 限制所有字段(文件除外)可以以字节为单位分配的内存量,如果超过此值,一个 'error' 事件将被触发,默认值:2mb (2 _ 1024 _ 1024)

  • uploadDir {String} 设置用于放置文件上载的目录, 默认值:os.tmpDir()

  • keepExtensions {Boolean} 写入 uploadDir 的文件将包括原始文件的扩展名,默认值:false

  • hashAlgorithm {String} 如果要计算传入文件的校验和,将其设置为“sha1”或“md5”,默认值:false

  • multiples {Boolean} 是否上载多个文件,默认值:true

  • onFileBegin {Function} 文件开始时的特殊回调。改函数将通过 formidable 执行,它可以用于在将文件保存到磁盘之前重命名文件

使用方法

bash

# 前端,项目中有demo。

# 终端命令,如
curl http://127.0.0.1:7071/controller/example/doHttpRequest?id=pictures
# 路由中的controller可以去掉
curl http://127.0.0.1:7071/example/doHttpRequest?id=pictures
# 控制器中加一层api目录
curl http://127.0.0.1:7071/api/test/hello

# 浏览器
http://127.0.0.1:7071/controller/example/doHttpRequest?id=pictures

SOCKET(一般走环信)

优点:双向通信

打开配置文件

bash

/* 内置socket服务 */
config.socketServer = {
  enable: false, // 是否启用
  port: 7070, // 默认端口(如果端口被使用,则随机获取一个)
  path: "/socket.io/", // 默认路径名称
  connectTimeout: 45000, // 客户端连接超时时间
  pingTimeout: 30000, // 心跳检测超时时间
  pingInterval: 25000, // 心跳检测间隔
  maxHttpBufferSize: 1e8, // 每条消息的数据最大值 1M
  transports: ["polling", "websocket"], // http轮询和websocket
  cors: {
    origin: true, // http协议时,要设置允许跨域
  }
};

使用方法

  • 在前端调用,访问 electron 业务层
bash

# vue
import { io } from 'socket.io-client'

export default {
  data() {
    return {};
  },
  mounted() {
    // socket支持http协议和websocket协议
    // 推荐使用websocket
    const url  = 'ws://127.0.0.1:' + port; // config中配置的端口
    this.socket = io(url, { transports: ["websocket"] });
    this.socket.on('connect', () => {
      console.log('connect!!!!!!!!');
    });
  },
  methods: {
    send() {
      const channel = 'c1'; // 通信频道固定
      const method = 'controller.example.hello'; // EE框架中,控制器中的方法
      this.socket.emit(channel, { cmd: method, params: 1 }, (response) => {
        // response为返回值
        console.log('response:', response)
      });
    }
  }
};
  • 方法二,在其他 node.js 中使用 socket.io 与 EE 框架通信
bash

# 第三方项目引入socket客户端
const Client = require('socket.io-client');

// socket支持http协议和websocket协议
// 推荐使用websocket
const url  = 'http://127.0.0.1:' + port;// config中配置的端口
const cObj = Client(url);

const channel = 'c1'; // 通信频道固定
const method = 'controller.example.hello'; // EE框架中,控制器中的方法
cObj.emit(channel, { cmd: method, params: 1 }, (response) => {
  // response为返回值
});
  • 方法三

通过走环信模块(或者其他第三方模块)