forked from nswbmw/N-chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
103 lines (92 loc) · 2.91 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
var users = [];//存储在线用户列表
app.get('/', function(req,res){
if(req.cookies.user == null){
//注意要有 return
return res.redirect('/signin');
}
res.sendfile('views/index.html');
});
app.get('/signin',function(req,res){
res.sendfile('views/signin.html');
});
app.post('/signin',function(req,res){
//检测该用户名是否已经存在于 users 数组中
if(users.indexOf(req.body.name) != -1){
//存在,则不允许登陆
res.redirect('/signin');
} else {
//不存在,把用户名存入 cookie 并跳转到主页
res.cookie("user",req.body.name,{maxAge:1000*60*60*24*30});
res.redirect('/');
}
});
var server = http.createServer(app);
var io = require('socket.io').listen(server);
io.sockets.on('connection',function(socket){
//有人上线
socket.on('online',function(data){
//将上线的用户名存储为 socket 对象的属性,以区分每个 socket 对象,方便后面使用
socket.name = data.user;
//数组中不存在该用户名则插入该用户名
if(users.indexOf(data.user) == -1){
users.unshift(data.user);
}
//向所有用户广播该用户上线信息
io.sockets.emit('online',{users:users,user:data.user});
});
//有人发话
socket.on('say',function(data){
if(data.to == 'all'){
//向其他所有用户广播该用户发话信息
socket.broadcast.emit('say',data);
} else {
//向特定用户发送该用户发话信息
//clients 为存储所有连接对象的数组
var clients = io.sockets.clients();
//遍历找到该用户
clients.forEach(function(client){
if(client.name == data.to){
//触发该用户客户端的 say 事件
client.emit('say',data);
}
});
}
});
//有人下线
socket.on('disconnect',function(){
//若 users 数组中保存了该用户名
if(users.indexOf(socket.name) != -1){
//从 users 数组中删除该用户名
users.splice(users.indexOf(socket.name),1);
//向其他所有用户广播该用户下线信息
socket.broadcast.emit('offline',{users:users,user:socket.name});
}
});
});
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});