-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathyjs-server.js
More file actions
64 lines (51 loc) · 1.56 KB
/
Copy pathyjs-server.js
File metadata and controls
64 lines (51 loc) · 1.56 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
const http = require('http');
const WebSocket = require('ws');
const Y = require('yjs');
const docs = new Map();
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Y.js WebSocket Server is running\n');
});
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws, req) => {
const docName = req.url.slice(1);
console.log(`Client connected to document: ${docName}`);
ws.docName = docName;
let doc = docs.get(docName);
if (!doc) {
doc = new Y.Doc();
docs.set(docName, doc);
console.log(`Created new document: ${docName}`);
}
// Send initial sync state to the client
const encoder = Y.encodeStateAsUpdate(doc);
if (encoder.length > 2) {
ws.send(encoder, { binary: true });
}
const updateHandler = (update, origin) => {
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN && client.docName === docName) {
client.send(update, { binary: true });
}
});
};
doc.on('update', updateHandler);
ws.on('message', (message) => {
try {
Y.applyUpdate(doc, new Uint8Array(message));
} catch (e) {
console.error('Failed to apply Y.js update:', e);
}
});
ws.on('close', () => {
doc.off('update', updateHandler);
console.log(`Client disconnected from document: ${docName}`);
});
ws.on('error', (error) => {
console.error('WebSocket error:', error);
});
});
const PORT = 1234;
server.listen(PORT, () => {
console.log(`Y.js WebSocket Server running on port ${PORT}`);
});