-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
82 lines (67 loc) · 1.83 KB
/
Copy pathserver.js
File metadata and controls
82 lines (67 loc) · 1.83 KB
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
import express from 'express';
import { Server } from 'socket.io';
import cors from 'cors';
import http from 'http';
import { connectdb } from './mongodb.js';
import { chatModel } from './chat.schema.js';
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: '*',
methods: ['GET', 'POST'],
},
});
connectdb();
// Maintain a list of connected users
const connectedUsers = new Set();
io.on('connection', (socket) => {
console.log('Connection is established');
socket.on('join', (data) => {
socket.username = data;
connectedUsers.add(socket.username);
// Notify all clients about the updated user count and list
io.emit('update_users', {
userCount: connectedUsers.size,
users: Array.from(connectedUsers),
});
chatModel
.find()
.sort({ timestamp: 1 })
.limit(50)
.then((messages) => {
console.log(messages);
socket.emit('load_messages', messages);
})
.catch((err) => {
console.log(err);
});
});
socket.on('new_message', (message) => {
let userMessage = {
username: socket.username,
message: message,
};
const newChat = new chatModel({
username: socket.username,
message: message,
timestamp: new Date(),
});
newChat.save().then(() => {
io.emit('broadcast_message', userMessage);
});
});
socket.on('disconnect', () => {
connectedUsers.delete(socket.username);
// Notify all clients about the updated user count and list
io.emit('update_users', {
userCount: connectedUsers.size,
users: Array.from(connectedUsers),
});
console.log('Connection is disconnected');
});
});
const PORT = process.env.PORT || 3300;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});