/
connection.js
112 lines (93 loc) · 2.85 KB
/
connection.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
110
111
112
var sys = require('sys'),
EventEmitter = require("events").EventEmitter,
net = require('net'),
ttransport = require('./transport'),
tprotocol = require('./protocol');
var BinaryParser = require('./binary_parser').BinaryParser;
BinaryParser.bigEndian = true;
var Connection = exports.Connection = function(stream, options) {
var self = this;
EventEmitter.call(this);
this.connection = stream;
this.options = options || {};
this.transport = this.options.transport || ttransport.TFramedTransport;
this.protocol = this.options.protocol || tprotocol.TBinaryProtocol;
this.offline_queue = [];
this.connected = false;
this.connection.addListener("connect", function() {
self.connected = true;
this.setTimeout(self.options.timeout || 0);
this.setNoDelay();
this.frameLeft = 0;
this.framePos = 0;
this.frame = null;
self.offline_queue.forEach(function(data) {
self.connection.write(data);
});
self.emit("connect");
});
this.connection.addListener("error", function(err) {
self.emit("error", err);
});
// Add a close listener
this.connection.addListener("close", function() {
self.emit("close");
});
this.connection.addListener("timeout", function() {
self.emit("timeout");
});
this.connection.addListener("data", self.transport.receiver(function(transport_with_data) {
var message = new self.protocol(transport_with_data);
try {
var header = message.readMessageBegin();
var dummy_seqid = header.rseqid * -1;
var client = self.client;
client._reqs[dummy_seqid] = function(err, success){
transport_with_data.commitPosition();
var callback = client._reqs[header.rseqid];
delete client._reqs[header.rseqid];
if (callback) {
callback(err, success);
}
};
client['recv_' + header.fname](message, header.mtype, dummy_seqid);
}
catch (e) {
if (e instanceof ttransport.InputBufferUnderrunError) {
transport_with_data.rollbackPosition();
}
else {
throw e;
}
}
}));
};
sys.inherits(Connection, EventEmitter);
Connection.prototype.end = function() {
this.connection.end();
}
Connection.prototype.write = function(data) {
if (!this.connected) {
this.offline_queue.push(data);
return;
}
this.connection.write(data);
}
exports.createConnection = function(host, port, options) {
var stream = net.createConnection(port, host);
var connection = new Connection(stream, options);
connection.host = host;
connection.port = port;
return connection;
}
exports.createClient = function(cls, connection) {
if (cls.Client) {
cls = cls.Client;
}
var client = new cls(new connection.transport(undefined, function(buf) {
connection.write(buf);
}), connection.protocol);
// TODO clean this up
connection.client = client;
return client;
}