-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
51 lines (41 loc) · 1.43 KB
/
server.js
File metadata and controls
51 lines (41 loc) · 1.43 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
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const cors = require('cors');
const app = express();
app.use(cors());
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
let document = ""; // Store the document content
wss.on('connection', (ws) => {
console.log('new client connected');
// Send the current version of the document to the newly connected client
ws.send(JSON.stringify({ type: 'init', data: document }));
ws.on('message', (message) => {
try {
const parsedMessage = JSON.parse(message);
if (parsedMessage.type === 'update') {
document = parsedMessage.data;
// Broadcast the update to all connected clients
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ type: 'update', data: document }));
}
});
}
} catch (error) {
console.error('Error parsing message:', error);
}
});
ws.on('close', () => {
console.log('client disconnected');
});
// Handle WebSocket errors
ws.on('error', (error) => {
console.error('WebSocket error:', error);
});
});
const PORT = 5001;
server.listen(PORT, () => {
console.log(`server listening on port ${PORT}`);
});