萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

基於 nw.js 構建桌面端聊天應用:從原理到實戰架構

為什麼選擇 nw.js?

  • Web 技術棧:HTML/CSS/JS 直接開發桌面應用
  • Node.js 集成:無縫調用 fs、net、child_process 等原生模塊
  • 跨平台:Windows/macOS/Linux 一套代碼
  • 無瀏覽器沙箱限制:可讀寫本地文件、啟動進程、系統托盤

核心架構設計

free-chat/
├── package.json          // 入口配置、窗口屬性、權限聲明
├── index.html            // 主窗口 UI
├── main.js               // 主進程邏輯(可選,nw.js 單進程模型)
├── renderer/             // 渲染進程代碼
│   ├── app.js            // Vue/React 入口
│   ├── components/       // 聊天列表、消息氣泡、側邊欄
│   └── utils/            // 加密、存儲、網絡
├── node_modules/         // 依賴(含原生模塊需 rebuild)
└── build/                // 打包輸出

關鍵技術點實現

1. 本地數據存儲(better-sqlite3 / IndexedDB)

// 主進程使用 Node 原生模塊
const Database = require('better-sqlite3');
const db = new Database('chat.db');
db.exec(`CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY, from_id TEXT, content TEXT, time INTEGER)`);

2. 實時通訊(WebSocket + 重連機制)

class ChatClient {
  constructor(url) {
    this.url = url;
    this.reconnectAttempts = 0;
    this.connect();
  }
  connect() {
    this.ws = new WebSocket(this.url);
    this.ws.onopen = () => this.reconnectAttempts = 0;
    this.ws.onmessage = (e) => this.handleMessage(JSON.parse(e.data));
    this.ws.onclose = () => this.scheduleReconnect();
  }
  scheduleReconnect() {
    const delay = Math.min(1000 * 2 ** this.reconnectAttempts++, 30000);
    setTimeout(() => this.connect(), delay);
  }
}

3. 系統托盤與原生通知

const nw = require('nw.gui');
const tray = new nw.Tray({icon: 'icon.png'});
tray.on('click', () => nw.Window.get().show());

// HTML5 Notification API(需用戶授權)
if (Notification.permission === 'granted') {
  new Notification('新消息', {body: '您有新消息', icon: 'avatar.png'});
}

4. 自動更新(nwjs-autoupdater)

const updater = require('nwjs-autoupdater');
updater.init({
  manifestUrl: 'https://myserver.com/app/manifest.json',
  checkInterval: 60 * 60 * 1000
});
updater.on('update-downloaded', () => updater.quitAndInstall());

打包發布流程

# 開發調試
nw .

# 生產打包(需安裝 nwjs-builder-phoenix)
npx nwjs-builder-phoenix . --platforms win64,mac64,linux64 --version 0.78.0

避坑指南

問題解決方案
原生模塊版本不匹配npm install --target_arch=x64 --target_platform=win32 或使用 electron-rebuild 同類工具
白屏/加載失敗檢查 CSP 政策,允許 unsafe-eval 或預編譯模板
Mac 簽名公證配置 macPlist、codesign、notarytool 流程
內存佔用高啟用 --disable-gpu、限制渲染進程、定期重啟
copyright © 萬盛學電腦網 all rights reserved