-
Notifications
You must be signed in to change notification settings - Fork 180
/
server.js
92 lines (73 loc) · 2.31 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const path = require('path');
const express = require('express');
const app = require('./backend/app');
const connectDatabase = require('./backend/config/database');
const PORT = process.env.PORT || 4000;
connectDatabase();
// deployment
__dirname = path.resolve();
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, '/frontend/build')))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'frontend', 'build', 'index.html'))
});
} else {
app.get('/', (req, res) => {
res.send('Server is Running! 🚀');
});
}
const server = app.listen(PORT, () => {
console.log(`Server Running on http://localhost:${PORT}`);
});
// ============= socket.io ==============
const io = require("socket.io")(server, {
// pingTimeout: 60000,
cors: {
origin: "http://localhost:3000",
}
});
let users = [];
const addUser = (userId, socketId) => {
!users.some((user) => user.userId === userId) &&
users.push({ userId, socketId });
}
const removeUser = (socketId) => {
users = users.filter((user) => user.socketId !== socketId);
}
const getUser = (userId) => {
return users.find((user) => user.userId === userId);
}
io.on("connection", (socket) => {
console.log("🚀 Someone connected!");
// console.log(users);
// get userId and socketId from client
socket.on("addUser", (userId) => {
addUser(userId, socket.id);
io.emit("getUsers", users);
});
// get and send message
socket.on("sendMessage", ({ senderId, receiverId, content }) => {
const user = getUser(receiverId);
io.to(user?.socketId).emit("getMessage", {
senderId,
content,
});
});
// typing states
socket.on("typing", ({ senderId, receiverId }) => {
const user = getUser(receiverId);
console.log(user)
io.to(user?.socketId).emit("typing", senderId);
});
socket.on("typing stop", ({ senderId, receiverId }) => {
const user = getUser(receiverId);
io.to(user?.socketId).emit("typing stop", senderId);
});
// user disconnected
socket.on("disconnect", () => {
console.log("⚠️ Someone disconnected")
removeUser(socket.id);
io.emit("getUsers", users);
// console.log(users);
});
});