-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
98 lines (84 loc) · 2.28 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const Moniker = require('moniker');
const app = express();
const server = http.Server(app);
const port = process.env.PORT || 3000;
const io = socketIO(server);
const currentTime = () => {
let date = new Date();
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
return hours+':'+minutes+':'+seconds;
};
app.get('/', (req, res) => {
res.sendFile(__dirname + '/client/index.html');
});
app.use(express.static('./client'));
server.listen(port, () => {
console.log('listening on *:' + port);
});
io.on('connection', socket=>{
const getList = () => {
const users = io.sockets.clients().connected;
return Object.keys(users).map(item => {
return users[item].username;
});
};
socket.username = Moniker.choose();
socket.on('change name',newName => {
let oldName = socket.username;
socket.username = newName;
socket.emit('set username',{
name: socket.username,
data: currentTime(),
users: getList(),
});
socket.broadcast.emit('user left', {
name:oldName,
data: currentTime(),
users: getList(),
});
socket.broadcast.emit('user joined', {
name:socket.username,
data: currentTime(),
users: getList(),
});
});
socket.emit('set username',{
name: socket.username,
data: currentTime(),
users: getList(),
});
socket.broadcast.emit('user joined', {
name:socket.username,
data: currentTime(),
users: getList(),
});
socket.on('disconnect', () => {
socket.broadcast.emit('user left', {
name:socket.username,
data: currentTime(),
users: getList(),
});
});
socket.on('chat message', (message) => {
socket.emit('status',{
status:'sent',
data:currentTime()
});
socket.broadcast.emit('chat message', {
name: socket.username,
message,
data: currentTime(),
});
}
);
socket.on('confirm',ct=>{
io.to(ct).emit('status',{status:'seen',data:currentTime()});
});
socket.on('typing', () => socket.broadcast.emit('typing', {name: socket.username}));
socket.on('stop typing', () => socket.broadcast.emit('stop typing', {name: socket.username}));
});