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