-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
85 lines (79 loc) · 2.3 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var users = {};
var usernames={};
// view engine setup
app.use(logger('dev'));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(favicon(path.join(__dirname, '/public/images/favicon.ico')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res) {
res.render('index');
});
app.get('/login', function(req, res) {
var name = req.query.name;
users[name] = name;
res.render('index');
});
app.get('/new', function(req, res) {
res.render('index');
});
//所有在线的user
io.on('connection', function(socket) {
console.log('a user connected');
socket.on('online', function(data) {
console.log(data);
socket.name = data.user;
if (!users[data.user]) {
console.log(socket.name+'已经存在');
users[data.user] = socket;
}
for(var i in users){
if(users[i].name){
usernames[i]=users[i].name;
}
}
console.log(usernames);
//向所有用户广播该用户上线信息
io.emit('online', {
user: data.user,
users: usernames
});
});
socket.on('chat message', function(msg) {
io.emit('chat message', msg);
});
socket.on('chat secret', function(data) {
for(var i in users){
if(users[i].name==data.from||users[i].name ==data.to){
users[i].emit('chat secret',data);
}
}
});
socket.on('disconnect', function() {
console.log('%s user disconnected',socket.name);
for(var i in users){
if(users[i].name==socket.name){
delete users[i];
delete usernames[socket.name];
}
}
io.emit('disconnect',{users: usernames})
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});