-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
90 lines (73 loc) · 2.59 KB
/
Copy pathserver.js
File metadata and controls
90 lines (73 loc) · 2.59 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const WebSocket = require('ws');
const Y = require('yjs');
const {setupWSConnection} = require('y-websocket/bin/utils');
const wss = new WebSocket.Server({port: 1234});
const collabSketches = new Map();
const serverUrl = "ws://pce-server.glitch.me/1234";
wss.on('connection', (ws, req) => {
console.log('New client connected');
const params = req.url.split('/');
console.log(params);
const roomID = params[1];
const userType = params[2];
if (userType === 'host') {
console.log('Host connected');
let yDoc = collabSketches.get(roomID);
if (!yDoc) {
yDoc = new Y.Doc();
console.log("Created new Y.Doc for sketch:", roomID);
collabSketches.set(roomID, yDoc);
console.log(yDoc.getText('codemirror'));
} else {
console.log("Existing document found, sending initial state to client.");
// If an existing document is found, send its initial state to the client
const encoder = Y.encodeStateAsUpdate(yDoc);
ws.send(encoder);
// Set up the connection with the document (yDoc)
setupWSConnection(ws, req, {
docName: roomID,
gc: true
}, yDoc);
}
} else if (userType === 'peer') {
console.log('Peer connected');
const yDoc = collabSketches.get(roomID);
if (yDoc) {
const encoder = Y.encodeStateAsUpdate(yDoc);
ws.send(encoder);
setupWSConnection(ws, req, {
docName: roomID,
gc: true
}, yDoc);
} else {
console.error('No document found for room:', roomID);
ws.send({error: 'No document found for room:' + roomID});
ws.close();
}
}
console.log('Active rooms:');
for (const [key, value] of collabSketches) {
console.log(`${key}`);
}
ws.on('close', () => {
console.log('Client disconnected');
});
});
console.log('WebSocket server running on ws://localhost:1234');
function parseWebSocketURL(url) {
try {
// Split the path to extract the room name and host
const pathParts = url.split('/').filter(Boolean);
if (pathParts.length >= 2) {
const roomName = pathParts[0];
const host = pathParts[1];
return {roomName, host};
} else {
throw new Error('Invalid URL format');
}
} catch (error) {
console.error('Error parsing WebSocket URL:', error);
return null;
}
}
module.exports = {documents: collabSketches};