-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclients.js
More file actions
64 lines (57 loc) · 1.53 KB
/
clients.js
File metadata and controls
64 lines (57 loc) · 1.53 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
var events = require('events'),
mongo = require('mongodb'),
ConnectionState = require('./croquet/connection').ConnectionState,
croquet = require('./croquet/croquet');
var socket;
// Client object
var Client = function(connection) {
this.id = connection.cid;
this.connection = connection;
this.state = {};
this.setMaxListeners(0);
};
Client.prototype = new events.EventEmitter();
Client.prototype.send = function(type, data) {
if (this.connection.state === ConnectionState.connected)
try { this.connection.send(type, data) }
catch(err) {}
};
init = function(server, handler) {
//initialize croquet
socket = new croquet.Croquet(server, '/croquet');
socket.on('connection', function(con) {
//init stuff, because javascript's hashes suck
var client = new Client(con);
//listen for messages
con.on('message', function(msg) {
try {
//dispatch the message
handler(client, msg.type, msg.data,
//success callback
function(val) {
msg.respond(val);
},
//error callback
function(err) {
msg.respondError(err);
});
} catch (err) {
console.log(err.stack);
console.log('');
}
});
//listen for disconnect
con.on('disconnect', function() {
client.emit('disconnect');
});
//update presence on pause/resume
con.on('pause', function() {
client.emit('pause');
});
con.on('resume', function() {
client.emit('resume');
});
});
};
//exports
exports.init = init;