← 教程列表
news

Task 2: Add HTTP server, file watching, and WebSocket connection handling

📅 2026/6/12 16:30:02⏱ 约 5 分钟阅读👁 8 阅读

**Files:** - Modify: `skills/brainstorming/scripts/server.js` - Test: `tests/brainstorm-server/server.test.js` (already exists) - [ ] **Step 1: Add configuration and constants at top of server.js (after requires)** ```js const http = require('http'); const fs = require('fs'); const path = require('path'); const PORT = process.env.BRAINSTORM_PORT || (49152 + Math.floor(Math.random() * 16383)); const HOST = process.env.BRAINSTORM_HOST || '127.0.0.1'; const URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST); const SCREEN_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm'; const MIME_TYPES = { '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml' }; ``` - [ ] **Step 2: Add WAITING_PAGE, template loading at module scope, and helper functions** Load `frameTemplate` and `helperInjection` at module scope so they're accessible to `wrapInFrame` and `handleRequest`. They only read files from `__dirname` (the scripts directory), which is valid whether the module is required or run directly. ```js const WAITING_PAGE = ` Brainstorm Companion

Brainstorm Companion

Waiting for Claude to push a screen...

`; const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8'); const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8'); const helperInjection = ''; function isFullDocument(html) { const trimmed = html.trimStart().toLowerCase(); return trimmed.startsWith('', content); } function getNewestScreen() { const files = fs.readdirSync(SCREEN_DIR) .filter(f => f.endsWith('.html')) .map(f => { const fp = path.join(SCREEN_DIR, f); return { path: fp, mtime: fs.statSync(fp).mtime.getTime() }; }) .sort((a, b) => b.mtime - a.mtime); return files.length > 0 ? files[0].path : null; } ``` - [ ] **Step 3: Add HTTP request handler** ```js function handleRequest(req, res) { if (req.method === 'GET' && req.url === '/') { const screenFile = getNewestScreen(); let html = screenFile ? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8')) : WAITING_PAGE; if (html.includes('')) { html = html.replace('', helperInjection + '\n'); } else { html += helperInjection; } res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(html); } else if (req.method === 'GET' && req.url.startsWith('/files/')) { const fileName = req.url.slice(7); // strip '/files/' const filePath = path.join(SCREEN_DIR, path.basename(fileName)); if (!fs.existsSync(filePath)) { res.writeHead(404); res.end('Not found'); return; } const ext = path.extname(filePath).toLowerCase(); const contentType = MIME_TYPES[ext] || 'application/octet-stream'; res.writeHead(200, { 'Content-Type': contentType }); res.end(fs.readFileSync(filePath)); } else { res.writeHead(404); res.end('Not found'); } } ``` - [ ] **Step 4: Add WebSocket connection handling** ```js const clients = new Set(); function handleUpgrade(req, socket) { const key = req.headers['sec-websocket-key']; if (!key) { socket.destroy(); return; } const accept = computeAcceptKey(key); socket.write( 'HTTP/1.1 101 Switching Protocols\r\n' + 'Upgrade: websocket\r\n' + 'Connection: Upgrade\r\n' + 'Sec-WebSocket-Accept: ' + accept + '\r\n\r\n' ); let buffer = Buffer.alloc(0); clients.add(socket); socket.on('data', (chunk) => { buffer = Buffer.concat([buffer, chunk]); while (buffer.length > 0) { let result; try { result = decodeFrame(buffer); } catch (e) { socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0))); clients.delete(socket); return; } if (!result) break; buffer = buffer.slice(result.bytesConsumed); switch (result.opcode) { case OPCODES.TEXT: handleMessage(result.payload.toString()); break; case OPCODES.CLOSE: socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0))); clients.delete(socket); return; case OPCODES.PING: socket.write(encodeFrame(OPCODES.PONG, result.payload)); break; case OPCODES.PONG: break; default: // Unsupported opcode — close with 1003 const closeBuf = Buffer.alloc(2); closeBuf.writeUInt16BE(1003); socket.end(encodeFrame(OPCODES.CLOSE, closeBuf)); clients.delete(socket); return; } } }); socket.on('close', () => clients.delete(socket)); socket.on('error', () => clients.delete(socket)); } function handleMessage(text) { let event; try { event = JSON.parse(text); } catch (e) { console.error('Failed to parse WebSocket message:', e.message); return; } console.log(JSON.stringify({ source: 'user-event', ...event })); if (event.choice) { const eventsFile = path.join(SCREEN_DIR, '.events'); fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n'); } } function broadcast(msg) { const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg))); for (const socket of clients) { try { socket.write(frame); } catch (e) { clients.delete(socket); } } } ``` - [ ] **Step 5: Add debounce timer map** ```js const debounceTimers = new Map(); ``` File watching logic is inlined in `startServer` (Step 6) to keep watcher lifecycle together with server lifecycle and include an `error` handler per spec. - [ ] **Step 6: Add startServer function and conditional main** `frameTemplate` and `helperInjection` are already at module scope (Step 2). `startServer` just creates the screen dir, starts the HTTP server, watcher, and logs startup info. ```js function startServer() { if (!fs.existsSync(SCREEN_DIR)) fs.mkdirSync(SCREEN_DIR, { recursive: true }); const server = http.createServer(handleRequest); server.on('upgrade', handleUpgrade); const watcher = fs.watch(SCREEN_DIR, (eventType, filename) => { if (!filename || !filename.endsWith('.html')) return; if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename)); debounceTimers.set(filename, setTimeout(() => { debounceTimers.delete(filename); const filePath = path.join(SCREEN_DIR, filename); if (eventType === 'rename' && fs.existsSync(filePath)) { const eventsFile = path.join(SCREEN_DIR, '.events'); if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile); console.log(JSON.stringify({ type: 'screen-added', file: filePath })); } else if (eventType === 'change') { console.log(JSON.stringify({ type: 'screen-updated', file: filePath })); } broadcast({ type: 'reload' }); }, 100)); }); watcher.on('error', (err) => console.error('fs.watch error:', err.message)); server.listen(PORT, HOST, () => { const info = JSON.stringify({ type: 'server-started', port: Number(PORT), host: HOST, url_host: URL_HOST, url: 'http://' + URL_HOST + ':' + PORT, screen_dir: SCREEN_DIR }); console.log(info); fs.writeFileSync(path.join(SCREEN_DIR, '.server-info'), info + '\n'); }); } if (require.main === module) { startServer(); } ``` - [ ] **Step 7: Run integration tests** The test directory already has a `package.json` with `ws` as a dependency. Install it if needed, then run tests. Run: `cd tests/brainstorm-server && npm install && node server.test.js` Expected: All tests pass - [ ] **Step 8: Commit** ```bash git add skills/brainstorming/scripts/server.js git commit -m "Add HTTP server, WebSocket handling, and file watching to server.js" ``` ---

← 返回教程列表 AI8899 · 内容仅供学习参考