-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.js
88 lines (75 loc) · 2.85 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
import express from 'express';
import { createServer } from 'node:http';
import { Server } from 'socket.io';
const app = express();
const server = createServer(app);
const io = new Server(server, {
cors: {
origin: '*',
}
});
//allow cors on app
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
// Store connected users and their socket IDs
const connectedUsers = new Map();
io.on('connection', (socket) => {
socket.on('userConnected', (user) => {
console.log(`${user.name} connected`);
connectedUsers.set(socket.id, user);
// Emit the list of connected users to all clients
io.emit('connectedUsers', Array.from(connectedUsers.values()));
});
socket.on('userDisconnected', (user) => {
console.log(`${user.name} disconnected`);
connectedUsers.delete(socket.id);
// Emit the list of connected users to all clients
io.emit('connectedUsers', Array.from(connectedUsers.values()));
});
socket.on('typing', (data) => {
const { from, to } = data;
const recipient = Array.from(connectedUsers.values()).find(user => user.id === to);
if (recipient) {
const recipientSocketId = Array.from(connectedUsers.entries()).find(([_, user]) => user.id === to)[0];
if (recipientSocketId) {
io.to(recipientSocketId).emit('typing', from);
} else {
//Recipient socket ID not found
}
} else {
// Recipient not found
}
});
socket.on('stopTyping', (data) => {
const { from, to } = data;
const recipient = Array.from(connectedUsers.values()).find(user => user.id === to);
if (recipient) {
const recipientSocketId = Array.from(connectedUsers.entries()).find(([_, user]) => user.id === to)[0];
io.to(recipientSocketId).emit('stopTyping', from);
}
});
socket.on('sendMessage', (data) => {
const { from, to, message } = data;
const recipient = Array.from(connectedUsers.values()).find(user => user.id === to);
if (recipient) {
const recipientSocketId = Array.from(connectedUsers.entries()).find(([_, user]) => user.id === to)[0];
io.to(recipientSocketId).emit('receiveMessage', { from, message });
}
});
socket.on('disconnect', () => {
const user = connectedUsers.get(socket.id);
if (user) {
connectedUsers.delete(socket.id);
io.emit('connectedUsers', Array.from(connectedUsers.values()));
}
});
});
app.get('/online-users', (req, res) => {
res.json(Array.from(connectedUsers.values()));
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});