-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
35 lines (29 loc) · 850 Bytes
/
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
const express = require('express');
const app = express();
//socket.io
const server = require('http').Server(app);
const io = require('socket.io')(server);
// 加入線上人數計數
let onlineCount = 0;
app.get('/', (req, res) => {
// res.send('Hello, World!');
res.sendFile(__dirname+'/views/index.html')
})
//當發生連線事件
io.on('connection', (socket) => {
onlineCount++;
io.emit('online', onlineCount);
socket.on('send', (msg) => {
console.log(msg);
if (Object.keys(msg).length < 2) return;
io.emit('msg',msg);
})
//當發生離線事件
socket.on('disconnect', () => {
onlineCount = (onlineCount < 0) ? 0 : onlineCount -= 1;
io.emit('online', onlineCount);
})
})
server.listen(3000, () => {
console.log("Server Started. http://localhost:3000")
})