forked from webtorrent/bittorrent-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
213 lines (178 loc) · 5.46 KB
/
Copy pathindex.js
File metadata and controls
213 lines (178 loc) · 5.46 KB
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
/* global Blob */
module.exports = Socket
var debug = require('debug')('simple-websocket')
var inherits = require('inherits')
var isTypedArray = require('is-typedarray')
var stream = require('stream')
var toBuffer = require('typedarray-to-buffer')
var ws = require('ws') // websockets in node - will be empty object in browser
var WebSocket = typeof window !== 'undefined' ? window.WebSocket : ws
inherits(Socket, stream.Duplex)
/**
* WebSocket. Same API as node core `net.Socket`. Duplex stream.
* @param {string} url websocket server url
* @param {Object} opts options to stream.Duplex
*/
function Socket (url, opts) {
var self = this
if (!(self instanceof Socket)) return new Socket(url, opts)
if (!opts) opts = {}
debug('new websocket: %s %o', url, opts)
opts.allowHalfOpen = false
stream.Duplex.call(self, opts)
self.url = url
self.connected = false
self.destroyed = false
self._chunk = null
self._cb = null
self._interval = null
self._ws = new WebSocket(self.url)
self._ws.binaryType = 'arraybuffer'
self._ws.onopen = self._onOpen.bind(self)
self._ws.onmessage = self._onMessage.bind(self)
self._ws.onclose = self._onClose.bind(self)
self._ws.onerror = self._onError.bind(self)
self.on('finish', function () {
if (self.connected) {
// When stream is finished writing, close socket connection. Half open connections
// are currently not supported.
// Wait a bit before destroying so the socket flushes.
// TODO: is there a more reliable way to accomplish this?
setTimeout(function () {
self._destroy()
}, 100)
} else {
// If socket is not connected when stream is finished writing, wait until data is
// flushed to network at "connect" event.
// TODO: is there a more reliable way to accomplish this?
self.once('connect', function () {
setTimeout(function () {
self._destroy()
}, 100)
})
}
})
}
Socket.prototype.send = function (chunk) {
var self = this
var len = chunk.length || chunk.byteLength || chunk.size
self._ws.send(chunk)
debug('write: %d bytes', len)
}
Socket.prototype.destroy = function (onclose) {
var self = this
self._destroy(null, onclose)
}
Socket.prototype._destroy = function (err, onclose) {
var self = this
if (self.destroyed) return
if (onclose) self.once('close', onclose)
debug('destroy (error: %s)', err && err.message)
self.connected = false
self.destroyed = true
clearInterval(self._interval)
self._interval = null
self._chunk = null
self._cb = null
if (self._ws) {
try {
self._ws.close()
} catch (err) {}
self._ws.onopen = null
self._ws.onmessage = null
self._ws.onclose = null
self._ws.onerror = null
}
self._ws = null
this.readable = this.writable = false
if (!self._readableState.ended) self.push(null)
if (!self._writableState.finished) self.end()
if (err) self.emit('error', err)
self.emit('close')
}
Socket.prototype._read = function () {}
/**
* Send text/binary data to the WebSocket server.
* @param {string|Buffer|TypedArrayView|ArrayBuffer|Blob} chunk
* @param {string} encoding
* @param {function} cb
*/
Socket.prototype._write = function (chunk, encoding, cb) {
var self = this
if (self.destroyed) return cb(new Error('cannot write after socket is destroyed'))
if (!isTypedArray.strict(chunk) && !(chunk instanceof ArrayBuffer) &&
!Buffer.isBuffer(chunk) && typeof chunk !== 'string' &&
(typeof Blob === 'undefined' || !(chunk instanceof Blob))) {
chunk = JSON.stringify(chunk)
}
if (self.connected) {
self.send(chunk)
if (typeof ws !== 'function' && self._ws.bufferedAmount) {
debug('start backpressure: bufferedAmount %d', self._ws.bufferedAmount)
self._cb = cb
} else {
cb(null)
}
} else {
debug('write before connect')
self._chunk = chunk
self._cb = cb
}
}
Socket.prototype._onMessage = function (event) {
var self = this
if (self.destroyed) return
var data = event.data
debug('read: %d bytes', data.byteLength || data.length)
if (data instanceof ArrayBuffer) {
data = toBuffer(new Uint8Array(data))
self.push(data)
} else if (Buffer.isBuffer(data)) {
self.push(data)
} else {
try {
data = JSON.parse(data)
} catch (err) {}
self.emit('data', data)
}
}
Socket.prototype._onOpen = function () {
var self = this
if (self.connected || self.destroyed) return
self.connected = true
if (self._chunk) {
self.send(self._chunk)
self._chunk = null
debug('sent chunk from "write before connect"')
var cb = self._cb
self._cb = null
cb(null)
}
// No backpressure in node. The `ws` module has a buggy `bufferedAmount` property.
// See: https://github.com/websockets/ws/issues/492
if (typeof ws !== 'function') {
self._interval = setInterval(function () {
if (!self._cb || !self._ws || self._ws.bufferedAmount) return
debug('ending backpressure: bufferedAmount %d', self._ws.bufferedAmount)
var cb = self._cb
self._cb = null
cb(null)
}, 150)
if (self._interval.unref) self._interval.unref()
}
debug('connect')
self.emit('connect')
}
Socket.prototype._onClose = function () {
var self = this
if (self.destroyed) return
debug('on close')
self._destroy()
}
Socket.prototype._onError = function () {
var self = this
if (self.destroyed) return
var err = new Error('connection error to ' + self.url)
debug('error: %s', err.message || err)
self._destroy(err)
}