44 lines
1.3 KiB
JavaScript
44 lines
1.3 KiB
JavaScript
const WebSocket = require("ws");
|
|
const wss = new WebSocket.Server({ port: 8080 });
|
|
|
|
const clients = new Map();
|
|
|
|
wss.on("connection", (ws, req) => {
|
|
console.log("New client connected");
|
|
|
|
ws.on("message", (message) => {
|
|
try {
|
|
const parsedMessage = JSON.parse(message);
|
|
if (parsedMessage.type === "register") {
|
|
clients.set(parsedMessage.userId, ws);
|
|
console.log(`User registered: ${parsedMessage.userId}`);
|
|
} else if (parsedMessage.type === "message") {
|
|
const recipientWs = clients.get(parsedMessage.recipientId);
|
|
if (recipientWs) {
|
|
recipientWs.send(
|
|
JSON.stringify({
|
|
senderId: parsedMessage.senderId,
|
|
message: parsedMessage.message,
|
|
timestamp: new Date().toISOString(),
|
|
})
|
|
);
|
|
} else {
|
|
console.error(`User ${parsedMessage.recipientId} is not connected.`);
|
|
}
|
|
}
|
|
} catch (err) {
|
|
console.error("Error processing message:", err.message);
|
|
}
|
|
});
|
|
|
|
ws.on("close", () => {
|
|
console.log("Client disconnected");
|
|
[...clients.entries()].forEach(([userId, clientWs]) => {
|
|
if (clientWs === ws) {
|
|
clients.delete(userId);
|
|
console.log(`User disconnected: ${userId}`);
|
|
}
|
|
});
|
|
});
|
|
});
|