probe-ws.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * 联调探针:接一条画面回传的 WebSocket,确认能收到二进制 JPEG 帧。
  3. *
  4. * node scripts/probe-ws.js <tabId> <cookie> [origin]
  5. *
  6. * 为什么不用现成的 WebSocket 客户端:浏览器/undici 的 WebSocket 不允许带自定义
  7. * 请求头,而这条连接必须带会话 cookie。所以这里手写握手(和 ws.js 对称)。
  8. */
  9. import net from 'node:net'
  10. import crypto from 'node:crypto'
  11. const [tabId, cookie, originArg] = process.argv.slice(2)
  12. if (!tabId || !cookie) {
  13. console.error('用法:node scripts/probe-ws.js <tabId> "<cc_sid=...>" [http://127.0.0.1:8787]')
  14. process.exit(1)
  15. }
  16. const origin = new URL(originArg || 'http://127.0.0.1:8787')
  17. const key = crypto.randomBytes(16).toString('base64')
  18. const socket = net.connect(Number(origin.port || 80), origin.hostname, () => {
  19. socket.write(
  20. `GET /_cc/rt?tab=${encodeURIComponent(tabId)} HTTP/1.1\r\n` +
  21. `Host: ${origin.host}\r\n` +
  22. 'Upgrade: websocket\r\nConnection: Upgrade\r\n' +
  23. `Sec-WebSocket-Key: ${key}\r\nSec-WebSocket-Version: 13\r\n` +
  24. `Cookie: ${cookie}\r\n\r\n`
  25. )
  26. })
  27. let handshaken = false
  28. let frames = 0
  29. let bytes = 0
  30. let buf = Buffer.alloc(0)
  31. const started = Date.now()
  32. socket.on('data', (chunk) => {
  33. buf = Buffer.concat([buf, chunk])
  34. if (!handshaken) {
  35. const idx = buf.indexOf('\r\n\r\n')
  36. if (idx < 0) return
  37. const head = buf.subarray(0, idx).toString('latin1')
  38. if (!/^HTTP\/1\.1 101/.test(head)) {
  39. console.error('握手失败:\n' + head)
  40. process.exit(2)
  41. }
  42. console.log('握手成功,等待画面…')
  43. handshaken = true
  44. buf = buf.subarray(idx + 4)
  45. }
  46. // 只统计"二进制帧",不解析内容:有帧就说明 CDP 回传链路通了
  47. while (buf.length >= 2) {
  48. const opcode = buf[0] & 0x0f
  49. let len = buf[1] & 0x7f
  50. let off = 2
  51. if (len === 126) { if (buf.length < 4) return; len = buf.readUInt16BE(2); off = 4 }
  52. else if (len === 127) { if (buf.length < 10) return; len = Number(buf.readBigUInt64BE(2)); off = 10 }
  53. if (buf.length < off + len) return
  54. const payload = buf.subarray(off, off + len)
  55. if (opcode === 0x2) {
  56. frames += 1
  57. bytes += payload.length
  58. if (frames === 1) console.log(`首帧 ${payload.length} 字节(JPEG 头 ${payload.subarray(0, 2).toString('hex')})`)
  59. } else if (opcode === 0x1) {
  60. console.log('控制消息:', payload.toString('utf8').slice(0, 200))
  61. }
  62. buf = buf.subarray(off + len)
  63. }
  64. })
  65. socket.on('error', (err) => {
  66. console.error('连接出错:' + err.message)
  67. process.exit(3)
  68. })
  69. setTimeout(() => {
  70. const seconds = ((Date.now() - started) / 1000).toFixed(1)
  71. console.log(`结果:${seconds}s 内收到 ${frames} 帧,共 ${(bytes / 1024).toFixed(1)} KB`)
  72. process.exit(frames > 0 ? 0 : 4)
  73. }, 6000)