- IPC
- define communication channel, i.e. route
- send request
- the request accesses the Hello function of the controller/example.js file
- define communication channel, i.e. route
- Send a message to the front-end
- front-end, demo in the project
- terminal commands, such as
- browser
- vue
- Third party project: introducing socket client
front-end and business layer you can communicate with each other in the following three ways:
- ipc
- http/https
- socket
IPC
advantages: bidirectional communication
file: ipcRender.js is introduced to the front-endOne-way communication
```define communication channel, i.e. route
const ipcApiRoute = { hello: ‘controller.example.hello’, }
send request
the request accesses the Hello function of the controller/example.js file
const self = this; this.$ipcInvoke(ipcApiRoute.hello, {name:’jack’}).then(r => { conson.log(r); })
<a name="ypSzR"></a>### **two-way communication **
define communication channel, i.e. route
const ipcApiRoute = { ipcSendMsg: ‘controller.example.ipcSendMsg’, }
// Avoid repeated monitoring, or set $IPC The on() function is written to a unified place and loaded only once this.$ipc.removeAllListeners(ipcApiRoute.ipcSendMsg);
// Listen and receive the data sent by the server event. Reply() this.$ipc.on(ipcApiRoute.ipcSendMsg, (event, result) => { console.log(‘[ipcRenderer] [ipcSendMsg] result:’, result);
self.messageString = result;// Call another interface of the back endevent.sender.send(ipcApiRoute.hello, 'electron-egg');
})
// Send a request to the server this.$ipc.send(ipcApiRoute.ipcSendMsg, ‘params’)
<a name="Nka8N"></a>### **Preload Module communication **
Send a message to the front-end
// channel const channel = ‘controller.example.ipcSendMsg’; // Use the webcontents Send() method eeApp.mainWindow.webContents.send(channel, {name:’jeck’});
electron ipc communication document <br />ipcMain: [https://www.electronjs.org/zh/docs/latest/api/ipc-main](https://www.electronjs.org/zh/docs/latest/api/ipc-main)<br />ipcRenderer: [https://www.electronjs.org/zh/docs/latest/api/ipc-renderer](https://www.electronjs.org/zh/docs/latest/api/ipc-renderer)<a name="oh5xv"></a>## HTTP/HTTPS**advantages**: cross-border access to EE programs in front-end, browser, terminal command (curl), etc. <br />**generate an ssl certificate**:[https://www.yuque.com/u34495/mivcfg/fppcdv](https://www.yuque.com/u34495/mivcfg/fppcdv)<a name="YaMDh"></a>### **open the configuration file**
/ Built-in HTTP service /
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
}
}
};
<a name="DS7Sc"></a>#### cors **properties**- 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
{ 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’], }
<a name="pCuWy"></a>#### body **properties **- 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执行,它可以用于在将文件保存到磁盘之前重命名文件。<a name="REbfv"></a>### **Usage**
front-end, demo in the project
terminal commands, such as
curl http://127.0.0.1:7071/controller/example/doHttpRequest?id=pictures
browser
http://127.0.0.1:7071/controller/example/doHttpRequest?id=pictures
<a name="twLjP"></a>## socket**advantages**: bidirectional communication<a name="Jg9Y1"></a>### **open the configuration file**
/ Built-in socket service / config.socketServer = { enable: false, port: 7070, path: “/socket.io/“, connectTimeout: 45000, pingTimeout: 30000, pingInterval: 25000, maxHttpBufferSize: 1e8, transports: [“polling”, “websocket”], cors: { origin: true, } };
<a name="cjZbB"></a>### **Usage **<a name="uLmjR"></a>#### **method 1 **call at the front end to access the electron business layer
vue
import { io } from ‘socket.io-client’
export default { data() { return {}; }, mounted() { // Socket supports HTTP protocol and websocket protocol 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’; // Fixed channel const method = ‘controller.example.hello’; // Methods in controller in EE framework this.socket.emit(channel, { cmd: method, params: 1 }, (response) => { console.log(‘response:’, response) }); } } };
<a name="N2kCm"></a>#### **Method 2**use socket.io to communicate with EE framework in other node.js projects
Third party project: introducing socket client
const Client = require(‘socket.io-client’);
const url = ‘http://127.0.0.1:’ + port;// Port in config const cObj = Client(url);
const channel = ‘c1’; const method = ‘controller.example.hello’; cObj.emit(channel, { cmd: method, params: 1 }, (response) => { // response }); ```
Method 3
network modules in other languages are similar, just listen to the communication address
