-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocketService.js
More file actions
67 lines (54 loc) · 2.02 KB
/
Copy pathsocketService.js
File metadata and controls
67 lines (54 loc) · 2.02 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
65
66
67
var redisClient = require('./redisClient');
var ChatService = require('./ChatService');
module.exports = function(http){
var socketClients = {}
ChatService.channelMessagesHandler(redisClient, socketClients);
var io = require('socket.io')(http);
// Authentication
io.use(function(socket, next) {
var nickname = socket.request._query.nickname;
var token = socket.request._query.token;
socketClients[token] = socket;
ChatService.connectClient(redisClient, nickname, token, function(status){
if(status == "OK"){
socketConnectionHandler(socket);
console.log("connection token validated for " + nickname + "#" + token);
next();
} else {
console.log("invalid connection token received: " + nickname + "#" + token);
next(new Error(status.error));
}
});
});
function socketConnectionHandler(socket){
var nickname = socket.handshake.query.nickname;
var token = socket.handshake.query.token;
console.log("client connected: " + nickname + "#" + token);
var chatClient = {
userToken: token,
client: socket // callback function that receives a message hash as parameter
}
var chatService = new ChatService(chatClient, redisClient);
socket.on("message", function(msg, ackFn){
if(Object.prototype.toString.call(msg) != '[object Object]'){
ackFn({error: "Invalid message. Should be a hash"});
return;
}
if(!msg.type){
ackFn({error: "Invalid message. Should provide a type"});
return;
}
chatService.processMessage(msg, ackFn);
});
socket.on("disconnect", function(msg){
// TODO: detect here that the user was doing a friendly disconnect in order to prevent him
// from being added to the list of users to be cleaned up.
delete socketClients[token];
chatService.setDisconnectedClient(token, function(status){
if(status == "OK"){
console.log("client disconnected: " + nickname + "#" + token);
}
});
});
}
};