-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
107 lines (81 loc) · 2.62 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import { config } from "dotenv";
config();
import express from "express";
import { Server } from "socket.io";
import { createServer } from "http";
const app = express();
import morgan from "morgan";
import cors from "cors";
import router from "./routes/routes.js"
import connectDatabase from "./config/config.js";
import { UserModel } from "./model/userModel.js";
connectDatabase(process.env.DB_URI);
const server = createServer(app);
app.use(cors({
origin: "*"
}));
app.use(express.json());
app.use(morgan("tiny"));
app.use(router);
app.get("/", (req, res) => {
res.json({
"message": "yooo"
})
})
const io = new Server(server, {
cors: {
origin: "http://localhost:5173"
}
})
//initial connect event
io.on("connection", async (socket) => {
// console.log(socket.handshake, "socket");
// console.log(socket.handshake.auth, "sockkkkk")
// socket.join(socket.handshake.auth._id);
console.log(socket.handshake.auth, "socketttt")
const { userData, chats } = socket.handshake.auth;
chats.forEach((chat) => {
socket.join(chat._id);
})
socket.emit("connection", { socketId: socket.id });
// socket.on("join-chat-room", ({ roomId }) => {
// socket.join(roomId);
// })
// console.log(io.sockets.sockets, "sockets")
socket.on("pvt-message", (msg) => {
console.log(msg, "msg")
// const clientsInRoom = io.sockets.adapter.rooms.get(msg.chatId);
// const isMultipleClients = clientsInRoom && clientsInRoom.size > 1;
io.to(msg.chatId).emit("pvt-message", msg);
// else{
// socket.to(msg.chatId).emit("pvt-message", msg);
// // socket.join(msg.toId);
// console.log("coollllllllllllllllllll")
// // io.to(msg.toId).to(msg.fromId).emit("pvt-message", msg);
// }
// // socket.join(msg.chatId);
// socket.join(msg.toId)
// console.log(clientsInRoom, "clinets")
// if (!isMultipleClients) {
// io.to(msg.toId).emit("pvt-message", msg)
// // io.to(msg.chatId).emit("pvt-message", msg)
// } else {
// io.to(msg.toId).emit("pvt-message", msg)
// }
})
socket.on("leave-room", ({ roomId }) => {
console.log("leaving", roomId)
socket.leave(roomId)
})
//disconnect event
socket.on("disconnect", (s) => {
console.log("user got disconnected")
})
})
// app.get("/delete", async(req, res)=>{
// await UserModel.deleteMany({});
// })
const PORT = process.env.PORT || 4000;
server.listen(PORT, () => {
console.log(`server listening to port ${PORT}`)
})