-
Notifications
You must be signed in to change notification settings - Fork 0
/
collaboration.js
66 lines (53 loc) · 1.64 KB
/
collaboration.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
require('dotenv').config();
const WebSocket = require('ws');
const PORT = process.env.PORT || 8080;
let documentContent = "";
let documentUpdatesLog = [];
function broadcastDocument(clients, content) {
clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
sendDocumentToClient(client, content);
}
});
}
function sendDocumentToClient(client, content) {
try {
client.send(JSON.stringify({ type: 'document', content }));
} catch (error) {
console.error('Error sending document to a client:', error);
}
}
function handleIncomingMessage(ws, message) {
console.log('Received:', message);
try {
const data = JSON.parse(message);
if (data.type === 'update') {
documentContent = data.content;
updateDocumentLog(data.content);
broadcastDocument(wss.clients, documentContent);
}
} catch (error) {
console.error('Error processing received message:', error);
}
}
function updateDocumentLog(content) {
const updateTimestamp = new Date().toISOString();
documentUpdatesLog.push({ updateTimestamp, content });
console.log(`Document updated at ${updateTimestamp}:`, content);
}
function getDocumentUpdateLogs() {
return documentUpdatesLog;
}
const wss = new WebSocket.Server({ port: PORT });
console.log(`WebSocket server started on port: ${PORT}`);
wss.on('connection', (ws) => {
console.log('Client connected');
sendDocumentToClient(ws, documentContent);
ws.on('message', (message) => handleIncomingMessage(ws, message));
ws.on('close', () => {
console.log('Client disconnected');
});
});
wss.on('error', (error) => {
console.error('WebSocket server error:', error);
});