-
-
Notifications
You must be signed in to change notification settings - Fork 309
/
websocket.js
109 lines (98 loc) · 2.5 KB
/
websocket.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
98
99
100
101
102
103
104
105
106
107
108
109
'use strict';
const debug = require('debug')('sockjs:trans:websocket');
const FayeWebsocket = require('faye-websocket');
const BaseReceiver = require('./base-receiver');
const Session = require('../session');
const middleware = require('../middleware');
class WebSocketReceiver extends BaseReceiver {
constructor(ws, socket) {
super(socket);
debug('new connection');
this.protocol = 'websocket';
this.ws = ws;
try {
socket.setKeepAlive(true, 5000);
} catch (x) {
// intentionally empty
}
this.ws.once('close', this.abort);
this.ws.on('message', (m) => this.didMessage(m.data));
this.heartbeatTimeout = this.heartbeatTimeout.bind(this);
}
tearDown() {
if (this.ws) {
this.ws.removeEventListener('close', this.abort);
}
super.tearDown();
}
didMessage(payload) {
debug('message');
if (this.ws && this.session && payload.length > 0) {
let message;
try {
message = JSON.parse(payload);
} catch (x) {
return this.close(3000, 'Broken framing.');
}
if (payload[0] === '[') {
message.forEach((msg) => this.session.didMessage(msg));
} else {
this.session.didMessage(message);
}
}
}
sendFrame(payload) {
debug('send');
if (this.ws) {
try {
this.ws.send(payload);
return true;
} catch (x) {
// intentionally empty
}
}
return false;
}
close(status = 1000, reason = 'Normal closure') {
super.close(status, reason);
if (this.ws) {
try {
this.ws.close(status, reason, false);
} catch (x) {
// intentionally empty
}
}
this.ws = null;
}
heartbeat() {
const supportsHeartbeats = this.ws.ping(null, () => clearTimeout(this.hto_ref));
if (supportsHeartbeats) {
this.hto_ref = setTimeout(this.heartbeatTimeout, 10000);
} else {
super.heartbeat();
}
}
heartbeatTimeout() {
if (this.session) {
this.session.close(3000, 'No response from heartbeat');
}
}
}
function sockjs_websocket(req, socket, head, next) {
const ws = new FayeWebsocket(req, socket, head, null, this.options.faye_server_options);
ws.once('open', () => {
// websockets possess no session_id
Session.registerNoSession(req, this, new WebSocketReceiver(ws, socket));
});
next();
}
module.exports = {
routes: [
{
method: 'GET',
path: '/websocket',
handlers: [middleware.websocket_check, sockjs_websocket],
transport: true
}
]
};