-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
61 lines (49 loc) · 1.53 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
import { Server } from "socket.io";
import dotenv from 'dotenv';
dotenv.config();
const PORT = process.env.PORT || 4000;
const io = new Server({
cors: {
origin: [
'https://true-estate-front-umber.vercel.app',
'https://true-estate-front-git-deploy-mashpotato9s-projects.vercel.app',
'http://localhost:5173'
],
methods: ["GET", "POST", "OPTIONS"],
credentials: true,
allowedHeaders: ["my-custom-header"],
transports: ['websocket', 'polling']
},
allowEIO3: true,
path: '/socket.io/'
});
let users = [];
const addUser = (userId, socketId) => {
const userExist = users.find(user => user.userId === userId);
if(!userExist) {
users.push({ userId, socketId });
}
};
const getUser = (userId) => {
return users.find(user => user.userId === userId);
};
const removeUser = (socketId) => {
users = users.filter(user => user.socketId !== socketId);
};
io.on("connection", (socket) => {
console.log('Client connected from:', socket.handshake.headers.origin);
socket.on("newUser", (userId) => {
addUser(userId, socket.id);
});
socket.on("sendMessage", ({ receiverId, data }) => {
const receiver = getUser(receiverId);
io.to(receiver.socketId).emit("getMessage", data);
});
socket.on("disconnect", () => {
removeUser(socket.id);
});
});
io.listen(PORT, () => {
console.log(`Socket server running on port ${PORT}`);
console.log('CORS origins:', io.options.cors.origin);
});