-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatServer.js
60 lines (48 loc) · 1.82 KB
/
chatServer.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
var socketIO = require("socket.io");
var verify = require("./routes/verify");
module.exports = function (httpServer) {
var io = socketIO(httpServer);
io.use(function (socket, next) {
var token = socket.request._query.token;
var auth = verify.verifyOrdinaryUser(token);
if (!auth.success) {
//could not verify user's identity
console.log(auth.error);
socket.disconnect();
return;
}
var username = auth.user._doc.username;
socket.username = username;
next();
});
io.on("connection", function (socket) {
var username = socket.username;
console.log('a user connected: ' + username);
/*
io.sockets.sockets becomes an object of Sockets with ID as the key
*/
var keys = Object.keys(io.sockets.sockets);//get an array of socket ID as Key
var onlineUsers = new Array(keys.length);
keys.forEach(function (idKey, i) {
var username = io.sockets.sockets[idKey].username;
onlineUsers[i] = username;
});
socket.emit("online users", JSON.stringify(onlineUsers));
socket.broadcast.emit("new user", username);
socket.on('disconnect', function () {
console.log('user disconnected: ' + this.username);
io.emit("user left", this.username);
});
socket.on("disconnect message", function () {
socket.disconnect();
});
socket.on("chat message", function (msg) {
//sends message to all chat users except for the sender of the message
socket.broadcast.emit("chat message", this.username + " said: " + msg);
});
});
process.on('SIGINT', function () {
console.log("closing chat server");
io.close();
});
}