-
Notifications
You must be signed in to change notification settings - Fork 15
/
server.js
48 lines (38 loc) · 1.25 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
/* eslint-disable no-console */
/* eslint-disable import/no-unresolved */
const path = require('path');
const express = require('express');
const app = express();
const server = require('http').Server(app);
const socket = require('socket.io');
const io = socket(server);
const PID = process.pid;
const PORT = process.env.PORT || 3000;
const users = {};
let usersNum = 0;
app.use(express.static(path.join(__dirname, 'public')));
// eslint-disable-next-line no-shadow
io.on('connection', (socket) => {
console.log(`The socket is connected! Socket id: ${socket.id}`);
usersNum += 1;
socket.on('new-user', (username) => {
io.emit('broadcast', `Online: ${usersNum}`);
users[socket.id] = username;
socket.broadcast.emit('user-connected', username);
});
socket.on('new-message', (data) => {
io.emit('new-message', data);
});
socket.on('is-typing', (username) => {
socket.broadcast.emit('is-typing', username);
});
socket.on('disconnect', () => {
usersNum -= 1;
io.emit('broadcast', `Online: ${usersNum}`);
socket.broadcast.emit('user-disconnected', users[socket.id]);
delete users[socket.id];
});
});
server.listen(PORT, () => {
console.log(`The server is Listening on http://localhost:${PORT} \nPID: ${PID}\n`);
});