-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
47 lines (37 loc) · 1.34 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
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const cors = require('cors');
const port = process.env.PORT || 5000;
app.use(express.json());
app.use(cors());
const http = require('http').createServer(app); // Creating HTTP server for both express and socket.io
const io = require("socket.io")(http, {
cors: {
origin: ["http://127.0.0.1:5500"],
}
});
const router = require('./routes/userRoute');
app.use("/api/user", router);
io.on('connection', (socket) => {
console.log('A user connected:', socket.id);
socket.on("chat", (data)=>{
socket.broadcast.emit("mes", data.message)
})
socket.on("server", (sender, message, reciever)=>{
io.emit(`${reciever}`, message, sender)
})
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
});
});
async function main() {
await mongoose.connect('mongodb+srv://rathodyuvraj1953:[email protected]/abcd?retryWrites=true&w=majority&appName=cluster-chat');
app.use("/", (req, res) => {
res.send("user data server is running");
});
}
main().then(() => console.log("MongoDB connected successfully")).catch(err => console.log(err));
http.listen(port, () => {
console.log(`Example app listening on port http://localhost:${port}`);
});