// ws-server.js
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
const clients = new Set();
wss.on('connection', (ws) => {
console.log('🚀 New client connected');
clients.add(ws);
ws.on('close', () => {
clients.delete(ws);
});
});
// 通知所有客户端刷新页面
function notifyClients() {
for (let client of clients) {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ type: 'update', message: 'new-version' }));
}
}
}
// 模拟触发更新(实际应在构建完成后调用)
setTimeout(() => {
console.log('🎉 New version released, notifying clients...');
notifyClients();
}, 10000); // 10 秒后触发
if ('WebSocket' in window) {
const ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => {
console.log('[WS] Connected to update server');
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'update') {
console.log('[WS] New version detected');
// 这里可以是弹窗提醒,或者直接刷新
if (confirm('检测到新版本,是否立即刷新页面?')) {
window.location.reload();
}
}
};
ws.onclose = () => {
console.log('[WS] Connection closed');
};
ws.onerror = (err) => {
console.error('[WS] Error:', err);
};
}