-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
49 lines (35 loc) · 1.08 KB
/
app.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
require('dotenv').config();
const express = require('express');
const app = express();
const path = require('path');
const http = require('http');
const { Server } = require('socket.io');
const server = http.createServer(app);
const io = new Server(server, {
connectionStateRecovery: {}
});
const PORT = process.env.PORT || 8000;
//Middleware
app.use(express.static(path.resolve('./public')));
let onlineUser = [];
io.on('connection', (socket) => {
onlineUser.push(socket.id);
io.emit('total-user', onlineUser.length);
socket.on('user-message', (message) => {
// console.log('Message received: ', message);
io.emit('backend-user-message', message, socket.id);
});
socket.on('disconnect', () => {
onlineUser = onlineUser.filter(id => id !== socket.id);
io.emit('total-user', onlineUser.length);
console.log('disconnected');
});
});
//express routes
app.get('/', (req, res) => {
res.sendFile('./public/index.html');
});
//listing to server
server.listen(PORT, () => {
console.log('\nServer is live on: ' + PORT);
})