-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
61 lines (45 loc) · 1.81 KB
/
index.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
// Goal: We'd like to use any transportation for freebird client/server communication
// msg is a string or a buffer
var util = require('util'),
EventEmitter = require('events');
function Transport() {
EventEmitter.call(this);
this._send = function (msg, callback) { // msg: { clientId: x, data: x }
throw new Error('Template method _send should be provided by implementor');
};
this._broadcast = this.send;
}
util.inherits(Transport, EventEmitter);
Transport.prototype.send = function (msg, callback) { // msg: { clientId: x, data: x }
if (typeof msg !== 'object')
return setImmediate(callback, new TypeError('msg must be an object with a data property'));
else
return this._send(msg, callback);
};
Transport.prototype.broadcast = function (msg, callback) { // msg: { data: x }
if (typeof msg !== 'object')
return setImmediate(callback, new TypeError('msg must be an object with a data property'));
else
return this._broadcast(msg, callback);
};
Transport.prototype.receive = function (msg, callback) { // msg: { clientId: x, data: x }
var self = this;
if (typeof msg !== 'object')
return setImmediate(callback, new TypeError('msg must be an object with a data property'));
setImmediate(function () {
if (typeof callback === 'function')
callback();
self.emit('message', msg);
});
};
Transport.prototype.unhandled = function (msg, callback) {
var self = this;
if (typeof msg !== 'object')
return setImmediate(callback, new TypeError('msg must be an object with a data property'));
setImmediate(function () {
if (typeof callback === 'function')
callback();
self.emit('unhandledMessage', msg);
});
};
module.exports = Transport;