-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathXHRPollingSocket.js
74 lines (67 loc) · 1.87 KB
/
XHRPollingSocket.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
var events = require('events')
, util = require('util')
, uuid = require('uuid')
module.exports = XHRPollingSocket
// ws should be open and valid
function XHRPollingSocket(ws) {
events.EventEmitter.call(this)
var self = this
this.buffer = []
this.is_closed = false
this.id = uuid.v1()
this.timeout = null
this.ws = ws
this.ws.once('close', function() {
console.log('websocket:close')
self.close()
})
this.ws.on('message', function(data) {
self.send_client(data)
})
}
util.inherits(XHRPollingSocket, events.EventEmitter)
XHRPollingSocket.prototype.close = function() {
if (!this.is_closed) {
this.buffer.push({event: 'close'})
if (this.client) {
this.set_client(this.client)
}
this.ws.removeAllListeners()
this.ws.close()
this.emit('close')
}
this.is_closed = true
}
XHRPollingSocket.prototype.send_ws = function(data) {
this.ws.send(data)
}
XHRPollingSocket.prototype.send_client = function(data) {
this.buffer.push({event: 'message', data: data})
if (this.client) {
this.set_client(this.client)
}
}
XHRPollingSocket.prototype.set_client = function(client) {
if (this.timeout) {
clearTimeout(this.timeout)
}
var self = this
if (this.buffer.length) {
client.json({events: this.buffer})
this.buffer = []
this.client = null
// we just had contact with this fella, so we're expecting a quick response
this.timeout = setTimeout(function() {
console.log('didn\'nt hear back, closing socket...')
self.close()
}, 5000)
} else {
this.client = client
// we've got a pending connection... but nothing to say, so let's hold it for a time and then send a heartbeat
this.timeout = setTimeout(function() {
console.log('sending heartbeat')
self.buffer.push({event: 'heartbeat'})
self.set_client(self.client)
}, 15000)
}
}