PageRenderTime 0ms CodeModel.GetById 103ms app.highlight 7ms RepoModel.GetById 24ms app.codeStats 0ms

/lib/socket.js

https://github.com/juliankrispel/node-chat
JavaScript | 54 lines | 40 code | 12 blank | 2 comment | 0 complexity | 3d9c992bb4597777f1d8839358e99685 MD5 | raw file
 1var EventEmitter = require('events').EventEmitter,
 2    _ = require('underscore');
 3
 4var sockets = {};
 5
 6var Socket = function(server){
 7    this.init(server);
 8}
 9
10_(Socket.prototype).extend(
11    EventEmitter.prototype, {
12
13    init: function(server){
14        _(this).bindAll('setupEvents', 'sendToClients', 'closeSocket');
15
16        this.io = require('socket.io').listen(server);
17        var that = this;
18        this.io.sockets.on('connection', function (socket) {
19            //Store socket in object
20            sockets[socket.id] = socket;
21
22            //Setup events for socket
23            that.setupEvents(socket);
24        });
25    },
26
27    closeSocket: function(id){
28        var socket = sockets[id];
29        socket.emit('Insufficient Credentials');
30        socket.disconnect();
31        delete socket[id];
32    },
33
34    setupEvents: function(socket){
35        var that = this;
36        socket.on('user_connected', function(data){
37            that.emit('user_connected', socket.id, data);
38        });
39
40        socket.on('message_from_user', function(data){
41            that.emit('message_from_user', socket.id, data);
42        });
43
44        socket.on('disconnect', function () {
45            that.emit('socket_disconnect', socket.id);
46        });
47    },
48
49    sendToClients: function(data){
50        this.io.sockets.emit('message_from_server', data);
51    }
52});
53
54module.exports = Socket;