-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
59 lines (55 loc) · 1.36 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
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
const TYPE_ENTER = 0;
const TYPE_LEAVE = 1;
const TYPE_MSG = 2;
var usersList = []
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
// 登录
socket.on('login',data=>{
var res = usersList.some(item=>{
return item.username === data.username
})
if(!res){
usersList.push(data)
socket.username = data.username
io.emit('loginSuccess',{
data,
usersList
})
}else{
socket.emit('loginFail',{
msg:'用户名被占用'
})
}
})
// 发消息
socket.on('getMsg',data=>{
io.emit('sendMsg',data)
})
// 断开
socket.on('disconnect',()=>{
console.log(socket.username)
usersList.forEach((item,index) => {
if(item.username === socket.username){
usersList.splice(index,1)
}
});
io.emit('userLeave',{
usersList,
data:{
username:socket.username,
type:TYPE_LEAVE,
time:Number(new Date().toLocaleTimeString().split(':')[0])>11?'下午'+new Date().toLocaleTimeString():'上午'+new Date().toLocaleTimeString()
}
});
})
});
http.listen(port, function(){
console.log('listening on *:' + port);
});