/** * 联调探针:接一条画面回传的 WebSocket,确认能收到二进制 JPEG 帧。 * * node scripts/probe-ws.js [origin] * * 为什么不用现成的 WebSocket 客户端:浏览器/undici 的 WebSocket 不允许带自定义 * 请求头,而这条连接必须带会话 cookie。所以这里手写握手(和 ws.js 对称)。 */ import net from 'node:net' import crypto from 'node:crypto' const [tabId, cookie, originArg] = process.argv.slice(2) if (!tabId || !cookie) { console.error('用法:node scripts/probe-ws.js "" [http://127.0.0.1:8787]') process.exit(1) } const origin = new URL(originArg || 'http://127.0.0.1:8787') const key = crypto.randomBytes(16).toString('base64') const socket = net.connect(Number(origin.port || 80), origin.hostname, () => { socket.write( `GET /_cc/rt?tab=${encodeURIComponent(tabId)} HTTP/1.1\r\n` + `Host: ${origin.host}\r\n` + 'Upgrade: websocket\r\nConnection: Upgrade\r\n' + `Sec-WebSocket-Key: ${key}\r\nSec-WebSocket-Version: 13\r\n` + `Cookie: ${cookie}\r\n\r\n` ) }) let handshaken = false let frames = 0 let bytes = 0 let buf = Buffer.alloc(0) const started = Date.now() socket.on('data', (chunk) => { buf = Buffer.concat([buf, chunk]) if (!handshaken) { const idx = buf.indexOf('\r\n\r\n') if (idx < 0) return const head = buf.subarray(0, idx).toString('latin1') if (!/^HTTP\/1\.1 101/.test(head)) { console.error('握手失败:\n' + head) process.exit(2) } console.log('握手成功,等待画面…') handshaken = true buf = buf.subarray(idx + 4) } // 只统计"二进制帧",不解析内容:有帧就说明 CDP 回传链路通了 while (buf.length >= 2) { const opcode = buf[0] & 0x0f let len = buf[1] & 0x7f let off = 2 if (len === 126) { if (buf.length < 4) return; len = buf.readUInt16BE(2); off = 4 } else if (len === 127) { if (buf.length < 10) return; len = Number(buf.readBigUInt64BE(2)); off = 10 } if (buf.length < off + len) return const payload = buf.subarray(off, off + len) if (opcode === 0x2) { frames += 1 bytes += payload.length if (frames === 1) console.log(`首帧 ${payload.length} 字节(JPEG 头 ${payload.subarray(0, 2).toString('hex')})`) } else if (opcode === 0x1) { console.log('控制消息:', payload.toString('utf8').slice(0, 200)) } buf = buf.subarray(off + len) } }) socket.on('error', (err) => { console.error('连接出错:' + err.message) process.exit(3) }) setTimeout(() => { const seconds = ((Date.now() - started) / 1000).toFixed(1) console.log(`结果:${seconds}s 内收到 ${frames} 帧,共 ${(bytes / 1024).toFixed(1)} KB`) process.exit(frames > 0 ? 0 : 4) }, 6000)