-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
92 lines (81 loc) · 2.54 KB
/
server.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const WebSocket = require('ws');
const express = require('express');
const path = require('path');
// Create an Express app
const app = express();
const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
// Serve static files from the 'public' folder
app.use(express.static(path.join(__dirname, 'public')));
// Create a WebSocket server
const wss = new WebSocket.Server({
server,
verifyClient: (info, done) => {
const origin = info.origin;
if (origin === 'http://localhost:3000' || origin === 'https://chatbox-nj7j.onrender.com') {
done(true);
} else {
done(false, 401, 'Unauthorized');
}
}
});
// When a WebSocket connection is made
wss.on('connection', (ws) => {
console.log('A user connected');
// Send a welcome message when a user connects
ws.send(JSON.stringify({
type: 'system',
message: 'Welcome to the chat app!',
timestamp: new Date().toLocaleTimeString()
}));
// When a message is received from the client
ws.on('message', (message) => {
try {
// Parse the incoming message
let parsedMessage = message;
if (message instanceof Buffer) {
parsedMessage = message.toString();
}
// Try to parse as JSON if it's a string
if (typeof parsedMessage === 'string') {
parsedMessage = JSON.parse(parsedMessage);
}
// Create the message data
const messageData = {
type: 'chat',
message: parsedMessage.message || parsedMessage,
sender: 'UserName',
timestamp: new Date().toLocaleTimeString(),
};
// Broadcast to ALL clients including sender
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(messageData));
}
});
} catch (error) {
console.error('Error processing message:', error);
}
});
// When a user disconnects
ws.on('close', () => {
console.log('A user disconnected');
// Optionally, inform all other clients about this disconnection
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
type: 'system',
message: 'A user has disconnected',
timestamp: new Date().toLocaleTimeString()
}));
}
});
});
// Handle WebSocket errors
ws.on('error', (error) => {
console.error('WebSocket error: ', error);
ws.close(); // Optionally close the connection on error
});
});