-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathclient.js
38 lines (29 loc) · 866 Bytes
/
client.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
'use strict';
//load websocket library if we are not in the browser
var WebSocket = require('./web-socket')
var duplex = require('./duplex')
var wsurl = require('./ws-url')
function isFunction (f) {
return 'function' === typeof f
}
module.exports = function (addr, opts) {
if (isFunction(opts)) opts = {onConnect: opts}
var location = typeof window === 'undefined' ? {} : window.location
var url = wsurl(addr, location)
var socket = new WebSocket(url)
var stream = duplex(socket, opts)
stream.remoteAddress = url
stream.close = function (cb) {
if (isFunction(cb)) {
socket.addEventListener('close', cb)
}
socket.close()
}
socket.addEventListener('open', function (e) {
if (opts && isFunction(opts.onConnect)) {
opts.onConnect(null, stream)
}
})
return stream
}
module.exports.connect = module.exports