Electron 接收 UDP 數據報
需求
Electron 可以自動接收服務器發送的廣播 UDP 數據報,當數據報的內容中有 'xxx' 字符串時,讀取該條數據報的數據內容並傳遞給渲染進程
實現
Electron 包含主進程和渲染進程
-
渲染進程中的頁面點擊讀取廣播 UDP 數據報按鈕(入口)
-
監聽入口按鈕,當入口按鈕被點擊時向主進程發送 listener 事件,獲取 UDP 數據報信息
-
主進程監聽到 listener 事件,調用 node 的 dgram 接口,dgram 接口可以獲取同一網關下的廣播 UDP 數據報,比對 UDP 數據報的內容是否符合條件,若符合條件則將數據傳送給渲染進程
-
渲染進程獲取到數據,根據數據進行一系列的處理操作
如果使主進程與渲染進程通信?
安裝 electron
npm install electron --save
index.html
加入以下代碼
<script>
window.electron = require('electron')
</script>
electron
的入口程序 main.js
中添加如下配置項
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true // add 集成 Nodejs
}
})
在 vue 組件中通過 ipcRenderer
與主進程通信
-
ipcRenderer.send('receiving-broadcast') 發送異步消息
-
ipcRenderer.on('broadcast-reply') 接收主進程傳遞過來的消息
const ipcRenderer = window.electron.ipcRenderer
ipcRenderer.send('receiving-broadcast')
ipcRenderer.on('broadcast-reply', (event, arg) => {
console.log(arg)
})
在 main.js 主進程中通過 ipcMain
與渲染進程通信
-
ipcMain.on('receiving-broadcast', (event, arg) => {}) 監聽渲染進程發送過來的事件
-
event.sender.send('broadcast-reply', JSON.stringify(rinfo)) 迴應渲染進程的異步消息
const dgram = require('dgram')
const {
ipcMain
} = require('electron')
ipcMain.on('receiving-broadcast', (event, arg) => {
// 調用 nodejs 的 dgram 接口接收 udp 數據報
// 套接字族爲 'udp4'
const socket = dgram.createSocket('udp4');
// 接收 UDP 數據報消息
socket.on('message', (msg, rinfo) => {
// 當數據報中數據包含 'bolean' 字符串時,將數據報的來源數據發送給渲染進程
if (~msg.indexOf('xxx')) {
event.sender.send('broadcast-reply', JSON.stringify(rinfo))
// 關閉 udp 監聽
socket.close()
}
});
// 綁定需要監聽的端口
socket.bind({
address: '0.0.0.0',
port: 9999
})
})