-
Notifications
You must be signed in to change notification settings - Fork 28
/
net.js
64 lines (56 loc) · 1.5 KB
/
net.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
'use strict';
var util = require('util');
var EventEmitter = require('events').EventEmitter;
function WebSocketProxy(url) {
var self = this;
EventEmitter.call(this);
this.sock = new WebSocket(url);
this.sock.addEventListener('open', function(e) {
self.emit('connect');
});
this.sock.addEventListener('message', function(e) {
self.emit('data', new Buffer(e.data));
});
this.sock.addEventListener('error', function(e) {
self.emit('error', e);
});
this.sock.addEventListener('close', function(e) {
self.emit('close');
});
}
util.inherits(WebSocketProxy, EventEmitter);
WebSocketProxy.prototype.end = function() {
this.destroy();
}
WebSocketProxy.prototype.destroy = function() {
if (
this.sock.readyState === WebSocket.CONNECTING ||
this.sock.readyState === WebSocket.OPEN
) {
this.sock.close();
}
}
WebSocketProxy.prototype.write = function(data) {
if (this.sock.readyState === WebSocket.OPEN) {
this.sock.send(data);
}
}
WebSocketProxy.prototype.pause = function() {
console.warn('WebSocketProxy stream pause/resume is not supported yet.');
}
WebSocketProxy.prototype.resume = function() {}
exports.createConnection = function(url) {
// The url is rebuilt to avoid including the auth credentials.
return new WebSocketProxy(url.format({
protocol: url.protocol,
slashes: url.slashes,
host: url.host,
hostname: url.hostname,
port: url.port,
pathname: url.pathname,
search: url.search,
path: url.path,
query: url.query,
hash: url.hash
}));
}