| 1 |
const WebSocket = require('ws'); |
| 2 |
const http = require('http'); |
| 3 |
const fs = require('fs'); |
| 4 |
const path = require('path'); |
| 5 |
|
| 6 |
|
| 7 |
const server = http.createServer((req, res) => { |
| 8 |
let filePath = '.' + req.url; |
| 9 |
|
| 10 |
|
| 11 |
const urlMap = { |
| 12 |
'/': './test/manual/ws.html', |
| 13 |
'/dist/htmx.js': './dist/htmx.js', |
| 14 |
'/src/ext/hx-ws.js': './src/ext/hx-ws.js', |
| 15 |
'/test/manual/ws.html': './test/manual/ws.html', |
| 16 |
}; |
| 17 |
|
| 18 |
if (urlMap[req.url]) { |
| 19 |
filePath = urlMap[req.url]; |
| 20 |
} |
| 21 |
|
| 22 |
console.log(`[${new Date().toISOString()}] HTTP ${req.method} ${req.url} -> ${filePath}`); |
| 23 |
|
| 24 |
const extname = String(path.extname(filePath)).toLowerCase(); |
| 25 |
const mimeTypes = { |
| 26 |
'.html': 'text/html', |
| 27 |
'.js': 'text/javascript', |
| 28 |
'.css': 'text/css', |
| 29 |
}; |
| 30 |
|
| 31 |
const contentType = mimeTypes[extname] || 'application/octet-stream'; |
| 32 |
|
| 33 |
fs.readFile(filePath, (error, content) => { |
| 34 |
if (error) { |
| 35 |
if (error.code === 'ENOENT') { |
| 36 |
res.writeHead(404); |
| 37 |
res.end('File not found: ' + filePath); |
| 38 |
} else { |
| 39 |
res.writeHead(500); |
| 40 |
res.end('Server error: ' + error.code); |
| 41 |
} |
| 42 |
} else { |
| 43 |
res.writeHead(200, { 'Content-Type': contentType }); |
| 44 |
res.end(content, 'utf-8'); |
| 45 |
} |
| 46 |
}); |
| 47 |
}); |
| 48 |
|
| 49 |
|
| 50 |
const wss = new WebSocket.Server({ server, clientTracking: true }); |
| 51 |
|
| 52 |
|
| 53 |
let counter = 0; |
| 54 |
const stocks = { |
| 55 |
HTMX: 142.50, |
| 56 |
AJAX: 98.30, |
| 57 |
REST: 67.80, |
| 58 |
GRPC: 112.40 |
| 59 |
}; |
| 60 |
|
| 61 |
|
| 62 |
function broadcast(channel, data) { |
| 63 |
wss.clients.forEach((client) => { |
| 64 |
if (client.readyState === WebSocket.OPEN && client.channel === channel) { |
| 65 |
client.send(JSON.stringify(data)); |
| 66 |
} |
| 67 |
}); |
| 68 |
} |
| 69 |
|
| 70 |
|
| 71 |
wss.on('connection', (ws, req) => { |
| 72 |
const url = req.url; |
| 73 |
console.log(`[${new Date().toISOString()}] New connection: ${url}`); |
| 74 |
|
| 75 |
|
| 76 |
ws.channel = url.replace('/', ''); |
| 77 |
|
| 78 |
|
| 79 |
switch (ws.channel) { |
| 80 |
case 'chat': |
| 81 |
handleChatConnection(ws); |
| 82 |
break; |
| 83 |
case 'notifications': |
| 84 |
handleNotificationsConnection(ws); |
| 85 |
break; |
| 86 |
case 'counter': |
| 87 |
handleCounterConnection(ws); |
| 88 |
break; |
| 89 |
case 'ticker': |
| 90 |
handleTickerConnection(ws); |
| 91 |
break; |
| 92 |
case 'dashboard': |
| 93 |
handleDashboardConnection(ws); |
| 94 |
break; |
| 95 |
default: |
| 96 |
console.log(`Unknown channel: ${ws.channel}`); |
| 97 |
} |
| 98 |
|
| 99 |
ws.on('message', (message) => { |
| 100 |
try { |
| 101 |
const data = JSON.parse(message); |
| 102 |
handleMessage(ws, data); |
| 103 |
} catch (e) { |
| 104 |
console.error('Error parsing message:', e); |
| 105 |
} |
| 106 |
}); |
| 107 |
|
| 108 |
ws.on('close', () => { |
| 109 |
console.log(`[${new Date().toISOString()}] Connection closed: ${ws.channel}`); |
| 110 |
}); |
| 111 |
|
| 112 |
ws.on('error', (error) => { |
| 113 |
console.error('WebSocket error:', error); |
| 114 |
}); |
| 115 |
}); |
| 116 |
|
| 117 |
|
| 118 |
function handleChatConnection(ws) { |
| 119 |
|
| 120 |
ws.send(JSON.stringify({ |
| 121 |
payload: '<div class="message received"><div>👋 Welcome to the chat!</div><div class="message-time">' + new Date().toLocaleTimeString() + '</div></div>' |
| 122 |
})); |
| 123 |
} |
| 124 |
|
| 125 |
|
| 126 |
let notificationInterval; |
| 127 |
function handleNotificationsConnection(ws) { |
| 128 |
const notifications = [ |
| 129 |
'📦 Package delivered', |
| 130 |
'👤 New follower', |
| 131 |
'💬 New comment on your post', |
| 132 |
'⭐ Someone starred your repository', |
| 133 |
'📧 You have new email', |
| 134 |
'🔔 Reminder: Meeting in 5 minutes', |
| 135 |
'✅ Build successful', |
| 136 |
'❌ Test failed', |
| 137 |
]; |
| 138 |
|
| 139 |
|
| 140 |
const sendNotification = () => { |
| 141 |
const notification = notifications[Math.floor(Math.random() * notifications.length)]; |
| 142 |
|
| 143 |
const html = `<div class="notification">${notification}<div class="notification-time">${new Date().toLocaleTimeString()}</div></div>`; |
| 144 |
|
| 145 |
broadcast('notifications', { |
| 146 |
payload: html |
| 147 |
}); |
| 148 |
|
| 149 |
setTimeout(sendNotification, 5000 + Math.random() * 3000); |
| 150 |
}; |
| 151 |
|
| 152 |
setTimeout(sendNotification, 3000); |
| 153 |
} |
| 154 |
|
| 155 |
|
| 156 |
function handleCounterConnection(ws) { |
| 157 |
|
| 158 |
ws.send(JSON.stringify({ |
| 159 |
payload: `<hx-partial id="counter">${counter}</hx-partial>` |
| 160 |
})); |
| 161 |
} |
| 162 |
|
| 163 |
|
| 164 |
function handleTickerConnection(ws) { |
| 165 |
|
| 166 |
const html = Object.entries(stocks).map(([symbol, price]) => |
| 167 |
`<div class="ticker-item"> |
| 168 |
<span class="ticker-symbol">${symbol}</span> |
| 169 |
<span class="ticker-price">$${price.toFixed(2)}</span> |
| 170 |
<span class="ticker-change up">+0.00%</span> |
| 171 |
</div>` |
| 172 |
).join(''); |
| 173 |
|
| 174 |
ws.send(JSON.stringify({ |
| 175 |
payload: `<hx-partial id="ticker">${html}</hx-partial>` |
| 176 |
})); |
| 177 |
|
| 178 |
|
| 179 |
const updatePrices = () => { |
| 180 |
Object.keys(stocks).forEach(symbol => { |
| 181 |
const change = (Math.random() - 0.5) * 5; |
| 182 |
stocks[symbol] = Math.max(10, stocks[symbol] + change); |
| 183 |
}); |
| 184 |
|
| 185 |
const html = Object.entries(stocks).map(([symbol, price]) => { |
| 186 |
const change = ((Math.random() - 0.5) * 5); |
| 187 |
const changePercent = (change / price * 100).toFixed(2); |
| 188 |
const changeClass = change >= 0 ? 'up' : 'down'; |
| 189 |
const changeSign = change >= 0 ? '+' : ''; |
| 190 |
|
| 191 |
return `<div class="ticker-item"> |
| 192 |
<span class="ticker-symbol">${symbol}</span> |
| 193 |
<span class="ticker-price">$${price.toFixed(2)}</span> |
| 194 |
<span class="ticker-change ${changeClass}">${changeSign}${changePercent}%</span> |
| 195 |
</div>`; |
| 196 |
}).join(''); |
| 197 |
|
| 198 |
broadcast('ticker', { |
| 199 |
payload: `<hx-partial id="ticker">${html}</hx-partial>` |
| 200 |
}); |
| 201 |
|
| 202 |
setTimeout(updatePrices, 2000 + Math.random() * 1000); |
| 203 |
}; |
| 204 |
|
| 205 |
setTimeout(updatePrices, 2000); |
| 206 |
} |
| 207 |
|
| 208 |
|
| 209 |
function handleDashboardConnection(ws) { |
| 210 |
|
| 211 |
const updateStats = () => { |
| 212 |
const cpu = Math.floor(Math.random() * 100); |
| 213 |
const memory = Math.floor(Math.random() * 100); |
| 214 |
const disk = Math.floor(Math.random() * 100); |
| 215 |
|
| 216 |
broadcast('dashboard', { |
| 217 |
payload: ` |
| 218 |
<hx-partial id="cpu">CPU: ${cpu}%</hx-partial> |
| 219 |
<hx-partial id="memory">Memory: ${memory}%</hx-partial> |
| 220 |
<hx-partial id="disk">Disk: ${disk}%</hx-partial> |
| 221 |
` |
| 222 |
}); |
| 223 |
|
| 224 |
setTimeout(updateStats, 1000); |
| 225 |
}; |
| 226 |
|
| 227 |
setTimeout(updateStats, 1000); |
| 228 |
} |
| 229 |
|
| 230 |
|
| 231 |
function handleMessage(ws, data) { |
| 232 |
console.log(`[${new Date().toISOString()}] Message from ${ws.channel}:`, data); |
| 233 |
|
| 234 |
if (ws.channel === 'chat') { |
| 235 |
|
| 236 |
if (data.values && data.values.message) { |
| 237 |
const message = data.values.message; |
| 238 |
|
| 239 |
const html = `<div class="message sent"><div>${escapeHtml(message)}</div><div class="message-time">${new Date().toLocaleTimeString()}</div></div>`; |
| 240 |
|
| 241 |
|
| 242 |
ws.send(JSON.stringify({ |
| 243 |
payload: html, |
| 244 |
request_id: data.request_id |
| 245 |
})); |
| 246 |
|
| 247 |
|
| 248 |
setTimeout(() => { |
| 249 |
const responses = [ |
| 250 |
'That\'s interesting! 🤔', |
| 251 |
'Tell me more! 💭', |
| 252 |
'I agree! 👍', |
| 253 |
'Awesome! 🎉', |
| 254 |
'Really? 😮', |
| 255 |
'Nice! ✨' |
| 256 |
]; |
| 257 |
const botResponse = responses[Math.floor(Math.random() * responses.length)]; |
| 258 |
|
| 259 |
const botHtml = `<div class="message received"><div>🤖 ${botResponse}</div><div class="message-time">${new Date().toLocaleTimeString()}</div></div>`; |
| 260 |
|
| 261 |
broadcast('chat', { |
| 262 |
payload: botHtml |
| 263 |
}); |
| 264 |
}, 1000); |
| 265 |
} |
| 266 |
} else if (ws.channel === 'counter') { |
| 267 |
|
| 268 |
const action = data.values?.action || data.action; |
| 269 |
|
| 270 |
if (action === 'increment') { |
| 271 |
counter++; |
| 272 |
} else if (action === 'decrement') { |
| 273 |
counter--; |
| 274 |
} else if (action === 'reset') { |
| 275 |
counter = 0; |
| 276 |
} |
| 277 |
|
| 278 |
|
| 279 |
broadcast('counter', { |
| 280 |
payload: `<hx-partial id="counter">${counter}</hx-partial>`, |
| 281 |
request_id: data.request_id |
| 282 |
}); |
| 283 |
} |
| 284 |
} |
| 285 |
|
| 286 |
|
| 287 |
function escapeHtml(unsafe) { |
| 288 |
return unsafe |
| 289 |
.replace(/&/g, "&") |
| 290 |
.replace(/</g, "<") |
| 291 |
.replace(/>/g, ">") |
| 292 |
.replace(/"/g, """) |
| 293 |
.replace(/'/g, "'"); |
| 294 |
} |
| 295 |
|
| 296 |
|
| 297 |
const PORT = 8080; |
| 298 |
server.listen(PORT, () => { |
| 299 |
console.log(` |
| 300 |
╔═══════════════════════════════════════════════════════════╗ |
| 301 |
║ ║ |
| 302 |
║ 🚀 HTMX WebSocket Demo Server ║ |
| 303 |
║ ║ |
| 304 |
║ HTTP Server: http://localhost:${PORT} ║ |
| 305 |
║ WebSocket Server: ws://localhost:${PORT} ║ |
| 306 |
║ ║ |
| 307 |
║ Open http://localhost:${PORT} in your browser ║ |
| 308 |
║ ║ |
| 309 |
╚═══════════════════════════════════════════════════════════╝ |
| 310 |
`); |
| 311 |
}); |
| 312 |
|