Building a chatApp using ws library.
Server.js
const http = require('http');
const WebSocket = require('ws'); // Import the 'ws' library
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('WebSocket servern');
});
const wss = new WebSocket.Server({ server });
// Array to store connected clients
const clients = [];
wss.on('connection', ws => {
console.log('Client connected');
// Add client to the list
clients.push(ws);
ws.on('message', message => {
console.log(`Received: ${message}`);
// Broadcast message to all clients except the sender
wss.clients.forEach(client => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
const dataToSend = JSON.stringify({ message, sender: 'server' });
client.send(dataToSend);
}
});
});
ws.on('close', () => {
console.log('Client disconnected');
removeClient(ws);
});
function removeClient(ws) {
const index = clients.indexOf(ws);
if (index !== -1) {
clients.splice(index, 1);
}
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
client.js
// client.js
let ws;
document.addEventListener('DOMContentLoaded', () => {
ws = new WebSocket('ws://localhost:3000');
const chatWindow = document.getElementById('chat-window');
// Event handler for incoming messages
ws.onmessage = event => {
const messageData = JSON.parse(event.data);
console.log('Received message data:', messageData); // Debugging log
const { message, sender } = messageData;
if (sender !== 'self') {
console.log('Appending message:', message); // Debugging log
appendMessage(messageData); // No need to pass chatWindow here
}
};
});
// Function to send a message
function sendMessage() {
const messageInput = document.getElementById('message-input');
const message = messageInput.value.trim();
if (message !== '') {
ws.send(JSON.stringify({ message }));
messageInput.value = '';
}
}
// Function to append a message to the chat window
function appendMessage(messageData) {
const chatWindow = document.getElementById('chat-window'); // Access chatWindow directly
const { message, sender } = messageData;
console.log('Appending actual message:', message);
const messageElement = document.createElement('div');
messageElement.textContent = `${sender}: ${message}`; // Display sender's name with the message
messageElement.classList.add('message-bubble');
chatWindow.appendChild(messageElement);
chatWindow.scrollTop = chatWindow.scrollHeight;
}
document.addEventListener('DOMContentLoaded', () => {
const sendButton = document.getElementById('send-btn');
sendButton.addEventListener('click', sendMessage);
});
On sending message to other sockets it is printing server: [object Object]
I am not able to get that also I logged the messages on the console
So this is the screenshot of the console. Not able to get what might be the issue. Is it in type conversion or some other element is causing issue.
For more info below is the index.html code to give a better view
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Real-Time Chat</title>
<link rel="stylesheet" href="styles.css">
<script src="./client.js"></script>
</head>
<body>
<div class="container">
<div id="chat-window" class="chat-box"></div>
<div class="input-container">
<input type="text" id="message-input" placeholder="Type your message...">
<button id="send-btn" onclick="sendMessage()">Send</button>
</div>
</div>
</body>
</html>