-
Notifications
You must be signed in to change notification settings - Fork 0
/
socketapi.js
42 lines (35 loc) · 1013 Bytes
/
socketapi.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
// Initialize Socket.IO
const io = require("socket.io")();
const socketapi = {
io: io,
};
const boards = {};
// Function to send the current board data to all clients in a room
function sendCurrentBoardData(roomId) {
if (boards[roomId]) {
io.to(roomId).emit('loadBoard', boards[roomId]);
}
}
// Handle socket connections
io.on('connection', (socket) => {
let currentBoard = null;
// Join a whiteboard room
socket.on('joinRoom', (roomId) => {
socket.join(roomId);
currentBoard = roomId;
sendCurrentBoardData(currentBoard); // Send current board data to the newly joined user
});
// Receive drawing data from a client
socket.on('draw', (data) => {
if (currentBoard) {
boards[currentBoard] = data;
// Broadcast the drawing data to all clients in the room (including the sender)
io.to(currentBoard).emit('draw', data);
}
});
// Handle disconnection
socket.on('disconnect', () => {
currentBoard = null;
});
});
module.exports = socketapi;