-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
68 lines (59 loc) · 1.83 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
const express = require('express')
const app = express()
const http = require('http').Server(app)
const io = require('socket.io')(http)
const path = require('path')
app.use(express.static(__dirname))
const webpack = require('webpack');
const config = require('./webpack.config');
const compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
})
// 在线用户
let onlineUser = {}
// 在线用户人数
let onlineCount = 0
io.on('connection', function (socket) {
// obj={uid:xxx.username:xxx}
socket.on('login', function (obj) {
if (!onlineUser.hasOwnProperty(obj.uid)) {
onlineUser[obj.uid] = obj.username
onlineCount++;
console.log(obj.username + ' 进入聊天室')
}
io.emit('login', {
onlineUser: onlineUser,
onlineCount: onlineCount,
username: obj.username
})
})
socket.on("sendChatMessage", function (obj) {
io.emit('sendChatMessage', obj)
console.log(obj.username + '说:' + obj.sendMessage)
})
socket.on('logout', function (obj) {
if (onlineUser.hasOwnProperty(obj.uid)) {
const user = {
uid: obj.uid,
username: onlineUser[obj.uid]
}
delete onlineUser[obj.uid]
onlineCount--
io.emit('logout', {
onlineUser: onlineUser,
onlineCount: onlineCount,
user: user
})
console.log(user.username + ' 退出了群聊', '还剩 ' + Object.values(onlineUser))
}
});
})
let port = 3000
http.listen(port, function () {
console.log('listening on port ' + port)
})