-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
76 lines (59 loc) · 1.92 KB
/
app.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
70
71
72
73
74
75
76
var express=require('express'),
app=express(),
server=require('http').createServer(app),
io=require('socket.io').listen(server);
users={};
var port = process.env.PORT || 8080;
server.listen(port);
app.use(express.static(__dirname + '/public'));
app.set('view engine','ejs');
app.get('/',function(req,res){
res.render('index');
});
io.sockets.on('connection',function(socket){
console.log("A New Connection Established");
socket.on('new user',function(data,callback){
if(data in users){
console.log("Username already taken");
callback(false);
}else{
console.log("Username available");
callback(true);
socket.nickname=data;
users[socket.nickname]=socket;
updateNicknames();
}
});
function updateNicknames(){
io.sockets.emit('usernames',Object.keys(users));
}
socket.on('send message',function(data,callback){
var msg=data.trim();
if(msg.substr(0,1) === '@'){
msg=msg.substr(1);
var ind=msg.indexOf(' ');
if(ind !== -1){
var name=msg.substring(0,ind);
var msg=msg.substring(ind+1);
if(name in users){
users[name].emit('whisper',{msg:msg,nick:socket.nickname});
socket.emit('private',{msg:msg,nick:name});
console.log("Whispering !");
}else{
callback("Sorry, "+name+" is not online");
}
}else{
callback("Looks like you forgot to write the message");
}
}
else{
console.log("Got Message :"+data)
io.sockets.emit('new message',{msg:msg,nick:socket.nickname});
}
});
socket.on('disconnect',function(data){
if(!socket.nickname) return;
delete users[socket.nickname];
updateNicknames();
});
});