-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
69 lines (42 loc) · 1.46 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
62
63
64
65
66
67
68
69
const PORT = process.env.PORT || 8080;
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var nicknames = [];
app.set('views engine', 'twig');
app.get('/', function(req, res){
res.render('index.html.twig');
});
io.on('connection', function(socket){
socket.on('new user', function(data, callback){
// check if nickname already exist
if (nicknames.indexOf(data) != -1) {
// if nickname is in the array, send false
callback(false);
} else {
callback(true);
// add the nickname into socket
socket.nickname = data;
//push it into the array
nicknames.push(socket.nickname);
// send the array to client
io.sockets.emit('usernames', nicknames);
}
});
socket.on('send message', function(data){
io.emit('new message', {msg: data, nick: socket.nickname});
});
function updateNicknames(){
};
socket.on('disconnect', function(data){
// send name of disconnected user to client
io.emit('userOff', socket.nickname);
// if the user never joined the room
if(!socket.nickname) return;
// if the user left the room, remove the nickname from the array
nicknames.splice(nicknames.indexOf(socket.nickname), 1);
})
});
http.listen(PORT, function(){
console.log(`listening on *:${PORT}`);
});