ws.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. /**
  2. * 最小 WebSocket 服务端
  3. * ====================
  4. * 只实现这条链路上用得到的部分:握手、文本/二进制帧、ping/pong、分片、关闭。
  5. * 为什么不引 ws:整台服务只跑一条业务 WS(画面回传),引一个库还要跟着它
  6. * 的版本升级;RFC 6455 的帧格式就这么多,写清楚比依赖更可控。
  7. */
  8. import crypto from 'node:crypto'
  9. const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
  10. function acceptKey (key) {
  11. return crypto.createHash('sha1').update(key + GUID).digest('base64')
  12. }
  13. /** 把服务端载荷编成一帧(服务端发出的帧不加掩码) */
  14. export function encodeFrame (payload, opcode = 0x1) {
  15. const data = Buffer.isBuffer(payload) ? payload : Buffer.from(String(payload), 'utf8')
  16. let header
  17. if (data.length < 126) {
  18. header = Buffer.alloc(2)
  19. header[1] = data.length
  20. } else if (data.length < 65536) {
  21. header = Buffer.alloc(4)
  22. header[1] = 126
  23. header.writeUInt16BE(data.length, 2)
  24. } else {
  25. header = Buffer.alloc(10)
  26. header[1] = 127
  27. header.writeBigUInt64BE(BigInt(data.length), 2)
  28. }
  29. header[0] = 0x80 | opcode
  30. return Buffer.concat([header, data])
  31. }
  32. export class WSConnection {
  33. constructor (socket, req, onMessage = () => {}) {
  34. this.socket = socket
  35. this.req = req
  36. this.closed = false
  37. this.buffer = Buffer.alloc(0)
  38. this.fragments = []
  39. this.fragmentOpcode = 0
  40. this.onMessage = onMessage
  41. this.onClose = () => {}
  42. socket.on('data', (chunk) => this.#feed(chunk))
  43. socket.on('close', () => this.#finish())
  44. socket.on('error', () => this.#finish())
  45. socket.setNoDelay(true)
  46. socket.setTimeout(0)
  47. }
  48. static accept (socket, req) {
  49. const key = req.headers['sec-websocket-key']
  50. if (!key) return null
  51. socket.write(
  52. 'HTTP/1.1 101 Switching Protocols\r\n' +
  53. 'Upgrade: websocket\r\n' +
  54. 'Connection: Upgrade\r\n' +
  55. `Sec-WebSocket-Accept: ${acceptKey(key)}\r\n\r\n`
  56. )
  57. return new WSConnection(socket, req)
  58. }
  59. get remoteAddress () {
  60. return this.socket.remoteAddress
  61. }
  62. send (payload, opcode = 0x1) {
  63. if (this.closed) return false
  64. try {
  65. this.socket.write(encodeFrame(payload, opcode))
  66. return true
  67. } catch {
  68. this.close()
  69. return false
  70. }
  71. }
  72. sendJSON (obj) {
  73. return this.send(JSON.stringify(obj), 0x1)
  74. }
  75. sendBinary (buf) {
  76. return this.send(buf, 0x2)
  77. }
  78. close () {
  79. if (this.closed) return
  80. try { this.socket.write(encodeFrame(Buffer.alloc(0), 0x8)) } catch { /* 已经断了 */ }
  81. this.#finish()
  82. try { this.socket.end() } catch { /* 已经断了 */ }
  83. }
  84. #finish () {
  85. if (this.closed) return
  86. this.closed = true
  87. try { this.onClose() } catch { /* 订阅方自己处理 */ }
  88. }
  89. #feed (chunk) {
  90. this.buffer = Buffer.concat([this.buffer, chunk])
  91. while (this.buffer.length >= 2) {
  92. const first = this.buffer[0]
  93. const second = this.buffer[1]
  94. const fin = (first & 0x80) !== 0
  95. const opcode = first & 0x0f
  96. const masked = (second & 0x80) !== 0
  97. let length = second & 0x7f
  98. let offset = 2
  99. if (length === 126) {
  100. if (this.buffer.length < 4) return
  101. length = this.buffer.readUInt16BE(2)
  102. offset = 4
  103. } else if (length === 127) {
  104. if (this.buffer.length < 10) return
  105. const big = this.buffer.readBigUInt64BE(2)
  106. if (big > BigInt(64 * 1024 * 1024)) { this.close(); return }
  107. length = Number(big)
  108. offset = 10
  109. }
  110. const maskSize = masked ? 4 : 0
  111. if (this.buffer.length < offset + maskSize + length) return
  112. const mask = masked ? this.buffer.subarray(offset, offset + 4) : null
  113. const start = offset + maskSize
  114. const payload = Buffer.from(this.buffer.subarray(start, start + length))
  115. if (mask) for (let i = 0; i < payload.length; i += 1) payload[i] ^= mask[i & 3]
  116. this.buffer = this.buffer.subarray(start + length)
  117. if (opcode === 0x8) { this.close(); return }
  118. if (opcode === 0x9) { this.send(payload, 0xa); continue }
  119. if (opcode === 0xa) continue
  120. if (opcode === 0x0) {
  121. this.fragments.push(payload)
  122. if (fin) {
  123. const merged = Buffer.concat(this.fragments)
  124. const kind = this.fragmentOpcode
  125. this.fragments = []
  126. this.fragmentOpcode = 0
  127. this.#deliver(kind, merged)
  128. }
  129. continue
  130. }
  131. if (!fin) {
  132. this.fragmentOpcode = opcode
  133. this.fragments = [payload]
  134. continue
  135. }
  136. this.#deliver(opcode, payload)
  137. }
  138. }
  139. #deliver (opcode, payload) {
  140. try {
  141. if (opcode === 0x1) this.onMessage(payload.toString('utf8'), false)
  142. else if (opcode === 0x2) this.onMessage(payload, true)
  143. } catch { /* 业务处理出错不能拖垮连接 */ }
  144. }
  145. }
  146. export function rejectUpgrade (socket, status = 401, text = 'Unauthorized') {
  147. try {
  148. socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: ${Buffer.byteLength(text)}\r\n\r\n${text}`)
  149. socket.destroy()
  150. } catch { /* 已经断了 */ }
  151. }