| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168 |
- /**
- * 最小 WebSocket 服务端
- * ====================
- * 只实现这条链路上用得到的部分:握手、文本/二进制帧、ping/pong、分片、关闭。
- * 为什么不引 ws:整台服务只跑一条业务 WS(画面回传),引一个库还要跟着它
- * 的版本升级;RFC 6455 的帧格式就这么多,写清楚比依赖更可控。
- */
- import crypto from 'node:crypto'
- const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
- function acceptKey (key) {
- return crypto.createHash('sha1').update(key + GUID).digest('base64')
- }
- /** 把服务端载荷编成一帧(服务端发出的帧不加掩码) */
- export function encodeFrame (payload, opcode = 0x1) {
- const data = Buffer.isBuffer(payload) ? payload : Buffer.from(String(payload), 'utf8')
- let header
- if (data.length < 126) {
- header = Buffer.alloc(2)
- header[1] = data.length
- } else if (data.length < 65536) {
- header = Buffer.alloc(4)
- header[1] = 126
- header.writeUInt16BE(data.length, 2)
- } else {
- header = Buffer.alloc(10)
- header[1] = 127
- header.writeBigUInt64BE(BigInt(data.length), 2)
- }
- header[0] = 0x80 | opcode
- return Buffer.concat([header, data])
- }
- export class WSConnection {
- constructor (socket, req, onMessage = () => {}) {
- this.socket = socket
- this.req = req
- this.closed = false
- this.buffer = Buffer.alloc(0)
- this.fragments = []
- this.fragmentOpcode = 0
- this.onMessage = onMessage
- this.onClose = () => {}
- socket.on('data', (chunk) => this.#feed(chunk))
- socket.on('close', () => this.#finish())
- socket.on('error', () => this.#finish())
- socket.setNoDelay(true)
- socket.setTimeout(0)
- }
- static accept (socket, req) {
- const key = req.headers['sec-websocket-key']
- if (!key) return null
- socket.write(
- 'HTTP/1.1 101 Switching Protocols\r\n' +
- 'Upgrade: websocket\r\n' +
- 'Connection: Upgrade\r\n' +
- `Sec-WebSocket-Accept: ${acceptKey(key)}\r\n\r\n`
- )
- return new WSConnection(socket, req)
- }
- get remoteAddress () {
- return this.socket.remoteAddress
- }
- send (payload, opcode = 0x1) {
- if (this.closed) return false
- try {
- this.socket.write(encodeFrame(payload, opcode))
- return true
- } catch {
- this.close()
- return false
- }
- }
- sendJSON (obj) {
- return this.send(JSON.stringify(obj), 0x1)
- }
- sendBinary (buf) {
- return this.send(buf, 0x2)
- }
- close () {
- if (this.closed) return
- try { this.socket.write(encodeFrame(Buffer.alloc(0), 0x8)) } catch { /* 已经断了 */ }
- this.#finish()
- try { this.socket.end() } catch { /* 已经断了 */ }
- }
- #finish () {
- if (this.closed) return
- this.closed = true
- try { this.onClose() } catch { /* 订阅方自己处理 */ }
- }
- #feed (chunk) {
- this.buffer = Buffer.concat([this.buffer, chunk])
- while (this.buffer.length >= 2) {
- const first = this.buffer[0]
- const second = this.buffer[1]
- const fin = (first & 0x80) !== 0
- const opcode = first & 0x0f
- const masked = (second & 0x80) !== 0
- let length = second & 0x7f
- let offset = 2
- if (length === 126) {
- if (this.buffer.length < 4) return
- length = this.buffer.readUInt16BE(2)
- offset = 4
- } else if (length === 127) {
- if (this.buffer.length < 10) return
- const big = this.buffer.readBigUInt64BE(2)
- if (big > BigInt(64 * 1024 * 1024)) { this.close(); return }
- length = Number(big)
- offset = 10
- }
- const maskSize = masked ? 4 : 0
- if (this.buffer.length < offset + maskSize + length) return
- const mask = masked ? this.buffer.subarray(offset, offset + 4) : null
- const start = offset + maskSize
- const payload = Buffer.from(this.buffer.subarray(start, start + length))
- if (mask) for (let i = 0; i < payload.length; i += 1) payload[i] ^= mask[i & 3]
- this.buffer = this.buffer.subarray(start + length)
- if (opcode === 0x8) { this.close(); return }
- if (opcode === 0x9) { this.send(payload, 0xa); continue }
- if (opcode === 0xa) continue
- if (opcode === 0x0) {
- this.fragments.push(payload)
- if (fin) {
- const merged = Buffer.concat(this.fragments)
- const kind = this.fragmentOpcode
- this.fragments = []
- this.fragmentOpcode = 0
- this.#deliver(kind, merged)
- }
- continue
- }
- if (!fin) {
- this.fragmentOpcode = opcode
- this.fragments = [payload]
- continue
- }
- this.#deliver(opcode, payload)
- }
- }
- #deliver (opcode, payload) {
- try {
- if (opcode === 0x1) this.onMessage(payload.toString('utf8'), false)
- else if (opcode === 0x2) this.onMessage(payload, true)
- } catch { /* 业务处理出错不能拖垮连接 */ }
- }
- }
- export function rejectUpgrade (socket, status = 401, text = 'Unauthorized') {
- try {
- socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: ${Buffer.byteLength(text)}\r\n\r\n${text}`)
- socket.destroy()
- } catch { /* 已经断了 */ }
- }
|