-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchatserver.js
60 lines (55 loc) · 1.5 KB
/
chatserver.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
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const port = 4001;
const index = require("./routes");
const moment = require("moment");
const app = express();
const server = http.createServer(app);
const cors = require("cors");
app.use(index);
app.use(cors({ origin: true, credentials: true }));
const io = socketIo(server, {
cors: {
origin: "*",
},
});
let users = [];
io.on("connection", (socket) => {
socket.on("joinRoom", ({ roomID, userName }) => {
socket.join(roomID);
users.push({
id: socket.id,
userName: userName,
connectionTime: new moment().format("YYYY-MM-DD HH:mm:ss"),
});
socket.on("sendMsg", (msgTo) => {
const minutes = new Date().getMinutes();
io.to(roomID).emit(
"message",
JSON.stringify({
id: socket.id,
userName: users.find((e) => e.id == msgTo.id).userName,
msg: msgTo.msg,
time:
new Date().getHours() +
":" +
(minutes < 10 ? "0" + minutes : minutes),
})
);
});
socket.on("leaveRoom", () => {
socket.offAny("sendMsg");
socket.leave(roomID);
});
});
socket.once("disconnect", () => {
let index = -1;
if (users.length >= 0) {
index = users.findIndex((e) => e.id == socket.id);
}
if (index >= 0) users.splice(index, 1);
io.emit("users", JSON.stringify(users));
});
});
server.listen(port, () => console.log(`Listening on port ${port}`));