electron-vue small test their skills

A recent project (vue) hardware requirements are triggered web page display terminal and switching effect, the customer's hardware only supports using tcp protocol communications, and it is our front-end does not take tcp, well-known in the browser, we only use http / https protocol (ajax) and websocket communications protocol, developed after the front page, I played a websocket node implements the project requirements, but after all, still have to use tcp ah. This time before you have to use colleagues said electron to build the entire project (before saw a demo of the package static files vue packaged into desktop applications). However, how the electron inside with a push data to tcp vue pages?

Colleagues also very enthusiastic, Baidu a better information, I also Baidu a lot, since the electron inside a tcp actually simple, demo offer:

 // TCP server 
var NET = the require ( ' NET ' );
 var Server = net.createServer (function (Connection) { 
   
   connection.on ( ' End ' , function () {
       // the console.log ( 'client closes '); 
   }); 
   connection.on ( ' data ' , function (data) {
     // the console.log (' server: receives data sent by the client ', data) 
   }) 
}); 
server.listen ( 9002 , function () { 
  the console.log ( ' Server IS Listening ' ); 
});

The net node module is provided, naturally and easily from a tcp service, and then send the information with test tools:

electron也是理所当然地收到了(上面tcp监听的是9002端口),但是怎么发给vue页面呢,下面奉上项目结构:

在index.js里面收到了通过tcp协议发来的消息,要推送倒Main.vuue页面,自然想到在该页面起一个事件监听器,当时想到的是用单例模式(vue的中央事件管理器)来处理,但是失败了。

后来在同事的帮助以及指导下,看到了类似如下截图使用的electron通讯方法:

然后就一直在这个ipcMain和ipcRenderer通讯上磨了好长时间,我们的需求是主进程给渲染进程发消息,但是!这个ipcMain居然只有事件监听,而且在主进程里面拿不到ipcRenderer这个对象(想着用这个在tcp里面给页面里面的ipcRenderer发消息)

期间还看了一篇博客(写得有点乱,自己封装了一些东西,但是博客里面写得不明不白,直接让我更加糊涂),多方查找无果之后,抛弃了上述的所有方法,乖乖地去看官方文档!!!

然后发现一个叫mainWindow.webContents的东西,这玩意儿就能给渲染进程(页面)发消息,后来才发现上述ipcMain的监听事件回调函数里面的event.sender对象,其实就是这个mainWindow.webContents;

so,主进程给渲染进程发消息只能通过mainWindow.webContents这个对象的send方法!!!跟ipcMain没有半毛钱关系!!!

所以,最终:

主进程:

渲染进程(页面):

至此,在electron内使用tcp实现主进程和渲染进程之间通讯已经告一段落,但是项目要打包成桌面应用啊,这块有几个坑需要注意一下:

1⃣️安装依赖不要使用淘宝镜像!!!使用淘宝镜像会疯狂报错!!!直接npm install,速度慢就速度吧(虽然不能用淘宝镜像,但是yarn貌似可以);

2⃣️用electron脚手架构建的项目,安装额外包的话,该依赖可能不会自动写到package.json文件里面去,所以项目npm install的话,没有自动写到配置文件的依赖不会下载,项目运行的话,不会报错,但是会一直显示一个文件目录的页面,个人建议,添加依赖之后,检查一下该依赖有没有自动写到配置文件里面去,没有的话手动添加一下,以免到时候除了问题半天查不出来;

3⃣️.electron-vue/webpack.renderer.config.js,打包成桌面应用之前,该文件122行的判断改成如下代码段:

nodeModules: path.resolve(__dirname, '../node_modules'),

4⃣️最后贡献两条electron-vue下桌面应用的打包脚本(win、mac平台):

"build-win": "node .electron-vue/build.js && electron-builder --win --x64",
"build-mac": "node .electron-vue/build.js && electron-builder --mac --x64",

 

谨以此记录首次electron开发遇到的诸多问题,好在最终还是解决遇到的所有问题,以后有空再用electron写点有意思的桌面应用吧。

Guess you like

Origin www.cnblogs.com/eco-just/p/11241789.html