-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
79 lines (66 loc) · 1.9 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
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
require("dotenv").config();
const express = require("express");
const app = express();
const http = require("http").createServer(app);
const io = require("socket.io")(http);
const port = process.env.PORT || 6954;
const bodyParser = require("body-parser");
const router = require('./routes/route')
const historySize = 100;
let history = [];
let typing = [];
let options = {
maxAge: '2y',
etag: false
}
app.set("view engine", "ejs");
app.set("views", "./views");
app.use(express.static('public', options));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/', router);
io.on("connection", (socket) => {
console.log("user connected");
socket.emit("history", history);
socket.on("message", (message) => {
while (history.length > historySize) {
// Remove the oldest message.
history.shift();
}
history.push(message);
io.emit("message", {
message: message.message,
name: message.name,
id: socket.id,
time: message.time,
});
});
socket.on("typing", (user) => {
let exists = false;
// Check if the user is already in the array.
typing.forEach((client) => {
if (client[1] == socket.id) {
exists = true;
}
});
if (user.typing && !exists) {
// Add the name and connection ID to the list of typing users.
typing.push([user.name, socket.id]);
} else if (!user.typing) {
// Remove the name and connection ID from the list of typing users.
typing.forEach((client, index) => {
if (client[1] == socket.id) {
// Remove the user from the list of typing users.
typing.splice(index, 1);
}
});
}
io.emit("typing", typing);
});
socket.on("disconnect", () => {
console.log(`user ${socket.id} disconnected`);
});
});
http.listen(port, () => {
console.log(`Example app listening on http://localhost:${port}`);
});