-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
67 lines (50 loc) · 1.57 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
const path = require('path');
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const bodyParser = require('body-parser');
const getTime = () => {
const d = new Date();
return `[${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()} ${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}]`;
}
const log = (msg) => {
const t = getTime();
console.log(`${t}: ${msg}`);
}
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res, next) => {
res.sendFile(__dirname + '/public/index.html');
});
io.on('connection', socket => {
socket.username = '';
socket.on('setUsername', username => {
socket.username = username;
log(`Set username: ${username}`);
socket.broadcast.emit('userConnected', {
username: socket.username
});
});
socket.on('disconnect', () => {
log(`The user ${socket.username} disconnect`);
});
socket.on('typing', () => {
log(`${socket.username} are typing...`);
socket.broadcast.emit('typing', {
username: socket.username
});
});
socket.on('stopTyping', () => {
log(`${socket.username} stop typing`);
socket.broadcast.emit('stopTyping', {
username: socket.username
});
});
socket.on('sendMessage', msg => {
socket.broadcast.emit('reciveMessage', msg);
});
});
http.listen(process.env.PORT || 3000, function(){
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});