-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
57 lines (47 loc) · 1.58 KB
/
Copy pathserver.js
File metadata and controls
57 lines (47 loc) · 1.58 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
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const path = require('path');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
let chatHistory = { window1: '', window2: '' };
let claimers = { window1: null, window2: null };
app.use(express.static(path.join(__dirname, 'public')));
io.on('connection', (socket) => {
console.log('A user connected');
// Send initial chat history
socket.emit('chatHistory', chatHistory);
socket.on('claimWindow', ({ window }) => {
if (!claimers[window]) {
claimers[window] = socket.id;
io.emit('windowClaimed', { window, userId: socket.id });
console.log(`User ${socket.id} claimed ${window}`);
}
});
socket.on('releaseWindow', ({ window }) => {
if (claimers[window] === socket.id) {
claimers[window] = null;
io.emit('windowReleased', { window, userId: socket.id });
console.log(`User ${socket.id} released ${window}`);
}
});
socket.on('typing', ({ window, text }) => {
if (claimers[window] === socket.id) {
chatHistory[window] = text;
io.emit('updateText', { window, text });
}
});
socket.on('disconnect', () => {
Object.keys(claimers).forEach((window) => {
if (claimers[window] === socket.id) {
claimers[window] = null;
io.emit('windowReleased', { window, userId: socket.id });
console.log(`User ${socket.id} disconnected and released ${window}`);
}
});
});
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});