|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const FayeWebsocket = require('faye-websocket'); |
| 4 | +const Session = require('../session'); |
| 5 | +const Transport = require('./transport'); |
| 6 | +const SockJSConnection = require('../sockjs-connection'); |
| 7 | + |
| 8 | +class RawWebsocketSessionReceiver { |
| 9 | + constructor(req, conn, server, ws) { |
| 10 | + this.ws = ws; |
| 11 | + this.prefix = server.options.prefix; |
| 12 | + this.readyState = Transport.OPEN; |
| 13 | + this.recv = { |
| 14 | + socket: conn, |
| 15 | + protocol: 'websocket-raw' |
| 16 | + }; |
| 17 | + |
| 18 | + this.connection = new SockJSConnection(this); |
| 19 | + Session.decorateConnection(req, this.connection, this.recv); |
| 20 | + server.emit('connection', this.connection); |
| 21 | + |
| 22 | + this._close = this._close.bind(this); |
| 23 | + this.ws.once('close', this._close); |
| 24 | + |
| 25 | + this.didMessage = this.didMessage.bind(this); |
| 26 | + this.ws.on('message', this.didMessage); |
| 27 | + } |
| 28 | + |
| 29 | + didMessage(m) { |
| 30 | + if (this.readyState === Transport.OPEN) { |
| 31 | + this.connection.emit('data', m.data); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + send(payload) { |
| 36 | + if (this.readyState !== Transport.OPEN) { |
| 37 | + return false; |
| 38 | + } |
| 39 | + this.ws.send(payload); |
| 40 | + return true; |
| 41 | + } |
| 42 | + |
| 43 | + close(status=1000, reason='Normal closure') { |
| 44 | + if (this.readyState !== Transport.OPEN) { |
| 45 | + return false; |
| 46 | + } |
| 47 | + this.readyState = Transport.CLOSING; |
| 48 | + this.ws.close(status, reason, false); |
| 49 | + return true; |
| 50 | + } |
| 51 | + |
| 52 | + _close() { |
| 53 | + if (!this.ws) { |
| 54 | + return; |
| 55 | + } |
| 56 | + this.ws.removeEventListener('message', this.didMessage); |
| 57 | + this.ws.removeEventListener('close', this._close); |
| 58 | + try { |
| 59 | + this.ws.close(1000, 'Normal closure', false); |
| 60 | + } catch (x) { |
| 61 | + // intentionally empty |
| 62 | + } |
| 63 | + this.ws = null; |
| 64 | + |
| 65 | + this.readyState = Transport.CLOSED; |
| 66 | + this.connection.emit('end'); |
| 67 | + this.connection.emit('close'); |
| 68 | + this.connection = null; |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +module.exports = { |
| 73 | + raw_websocket(req, socket, head, next) { |
| 74 | + const ver = req.headers['sec-websocket-version'] || ''; |
| 75 | + if (['8', '13'].indexOf(ver) === -1) { |
| 76 | + return next({ |
| 77 | + status: 400, |
| 78 | + message: 'Only supported WebSocket protocol is RFC 6455.' |
| 79 | + }); |
| 80 | + } |
| 81 | + const ws = new FayeWebsocket(req, socket, head, null, |
| 82 | + this.options.faye_server_options); |
| 83 | + ws.onopen = () => { |
| 84 | + new RawWebsocketSessionReceiver(req, socket, this, ws); |
| 85 | + }; |
| 86 | + next(); |
| 87 | + } |
| 88 | +}; |
0 commit comments