-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
68 lines (57 loc) · 1.65 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 http = require('http');
const Server = require('socket.io');
const express = require('express');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
app.use(express.static('public'));
app.get('/', (req, res) => {
res.sendFile(`${__dirname}/public/index.html`);
});
const users = new Map();
io.on('connection', socket => {
console.log('a user connected');
socket.on('join', nickname => {
console.log('a user joined');
users.set(socket.id, nickname);
socket.join('general');
socket.to('general').emit('message', {
type: 'system',
nickname,
body: 'has joined.',
timestamp: Date.now(),
});
io.emit('online-users', [...users]);
});
socket.on('typing', status => {
console.log('a user is typing');
const nickname = users.get(socket.id);
socket.to('general').emit('typing', { nickname, status });
});
socket.on('message', messageBody => {
console.log(`message: ${messageBody}`);
const nickname = users.get(socket.id);
socket.to('general').emit('typing', { nickname, status: false });
socket.to('general').emit('message', {
type: 'chat',
nickname,
body: messageBody,
timestamp: Date.now(),
});
});
socket.on('disconnect', () => {
const nickname = users.get(socket.id);
socket.to('general').emit('message', {
type: 'system',
nickname,
body: 'has left.',
timestamp: Date.now(),
});
users.delete(socket.id);
socket.broadcast.emit('online-users', [...users]);
console.log('user disconnected');
});
});
server.listen(3000, () => {
console.log('listening on *:3000');
});