-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
83 lines (69 loc) · 2.08 KB
/
server.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
const server = require('http').createServer((req, res) => {
handle(req, res, req.url)
});
const io = require('socket.io')(server)
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
let userList = [];
app.prepare().then(() => {
server.listen(3333, (err) => {
if (err) throw err
console.log('> Ready on http://localhost:3333')
})
io.on('connection', socket => {
console.log(socket.id)
socket.on('connectUser', user => {
console.log(`${user.userName}连接进来`);
if (user) {
if (!userList.map(item => item.userId).includes(user.id)) {
userList.unshift({
userName: user.userName,
userId: user.id,
socketId: socket.id
});
} else {
userList.splice(userList.map(item => item.userId).indexOf(user.id), 1, {
userName: user.userName,
userId: user.id,
socketId: socket.id
});
}
}
io.emit('userList', userList);
})
socket.on('removeUser', name => {
console.log(`${name}连接断开`);
if (userList.map(item => item.name).includes(name)) {
userList.splice(userList.map(item => item.name).indexOf(name), 1);
}
io.emit('userList', userList);
})
socket.on("private message", (msg) => {
console.log(msg);
socket.volatile.to(msg.toSockedId).emit("private message", msg);
});
socket.on('event', data => {
console.log('event', data);
});
socket.on('disconnect', (data) => {
console.log('disconnect', data);
});
socket.on('createGroup', ({ groupName, selectUserList }) => {
let id = +new Date()
selectUserList.forEach(item => io.to(item.id).emit('joinGroup', {
groupName,
id
}))
})
socket.on('joinGroup', res => {
socket.join(res.id);
console.log("加入群组:" + res.id);
})
socket.on('sendGroupMsg', res => {
console.log(res);
io.to(res.id).emit('groupMsg', res)
})
});
})