Websocket (Node.js)

This Node.js WebSocket server enables real-time communication between clients. Clients are assigned unique IDs upon connection, and messages, including image uploads, are broadcasted to all connected clients. Additionally, the server logs messages to a text file for reference, enhancing communication capabilities for applications requiring real-time updates.

Usage

1. Real-Time Chat Application with WebSocket Logging in Node.js
const WebSocket = require("ws");
const http = require("http");
const fs = require("fs");
const { v4: uuidv4 } = require("uuid");
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("WebSocket server is running");
});
const wss = new WebSocket.Server({ server });
const loggingFilePath = "websocket_logs.txt";
// Keep track of connected clients
const clients = new Set();
wss.on("connection", (ws, req) => {
const userId = uuidv4();
console.log('User#-userId connected');
const clientIp = req.socket.remoteAddress;
// Add the new client to the set
clients.add(ws);
// Event listener for receiving messages
ws.on("message", (message) => {
const messageObj = JSON.parse(message);
if (messageObj.type == "image") {
logMessage(userId, "sended image");
} else {
logMessage(userId, messageObj.message);
}
broadcast(
JSON.stringify({
user: userId,
message: messageObj,
client_ip: clientIp,
})
);
});
// Event listener for closing the connection
ws.on("close", () => {
console.log("Client disconnected");
// Remove the disconnected client from the set
clients.delete(ws);
});
});
function logMessage(userId, message) {
const logEntry = 'Date: UserID-Message';
// Append the log entry to the file
fs.appendFile(loggingFilePath, logEntry, (err) => {
if (err) {
console.error("Error writing to log file:", err);
}
});
}
// Broadcast a message to all connected clients
function broadcast(message) {
clients.forEach((client) => {
// Check if the client is still connected before sending the message
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
}
const PORT = 3000;
server.listen(PORT, () => {
console.log('Server listening on http://localhost:PORT');
});
This Node.js project implements a real-time chat application using WebSocket technology. The application allows multiple users to connect simultaneously and exchange messages in real-time. Each user is assigned a unique identifier (UUID) upon connection, facilitating personalized interactions within the chat. Additionally, the application incorporates logging functionality to track user activities. Messages exchanged between users, including image uploads, are logged along with timestamps and user IDs. These logs are appended to a designated file (websocket_logs.txt) for future reference and analysis. The server utilizes the WebSocket module to establish bidirectional communication channels between the server and connected clients. When a client sends a message, it is broadcasted to all other connected clients, enabling seamless communication among users. This project showcases the power of WebSocket technology for building efficient real-time communication systems and demonstrates how to integrate logging functionality for monitoring and analyzing user interactions.