shantanu srivastava
shantanu srivastava

Reputation: 193

Displaying [object Blob] instead of the message in chatApp built using ws module

I am using ws module rather than the popular socket.io module to built a chat app. But it is not displaying the message I am sending rather it is showing "[object Blob]".I have also added console.logs() but it is not logging anything.
Frontend Code
index.html

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat Application</title>
</head>
<body>
    <div id="chat-container">
        <div id="chat-messages"></div>
        <input type="text" id="message-input" placeholder="Type your message">
        <button id="send-button">Send</button>
    </div>

    <script src="client.js"></script>
</body>
</html>

client.js

// WebSocket connection URL
const socket = new WebSocket('ws://localhost:5000');

// Elements
const messageInput = document.getElementById('message-input');
const sendButton = document.getElementById('send-button');
const chatMessages = document.getElementById('chat-messages');

// Event listener for WebSocket connection established
socket.addEventListener('open', () => {
  console.log('Connected to server');
});

// Event listener for send button click
sendButton.addEventListener('click', () => {
  const message = messageInput.value.trim();
  if (message !== '') {
    sendMessage(message);
    messageInput.value = '';
  }
});

// Event listener for incoming messages from the server
socket.addEventListener('message', (event) => {
  const message = event.data;
  console.log('Received message:', message);
  
  if (typeof message === 'string') {
    // If the message is a string, display it directly
    displayMessage(message);
  } else {
    // If the message is a Blob, handle it accordingly
    handleBlobMessage(message);
  }
});

// Function to send a message to the server
function sendMessage(message) {
  socket.send(message);
}

// Function to display a message in the chat
function displayMessage(message) {
  const messageElement = document.createElement('div');
  messageElement.textContent = message;
  chatMessages.appendChild(messageElement);
}

// Function to handle Blob messages
function handleBlobMessage(blob) {
  console.log('Received Blob:', blob);
  const reader = new FileReader();
  reader.onload = function () {
    const text = reader.result;
    console.log('Converted Blob to text:', text);
    displayMessage(text);
  };
  reader.readAsText(blob);
}

Backend Code
server.js

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 5000 });

// Create an array to store connected clients
const clients = [];

// Event listener for WebSocket connections
wss.on('connection', (ws) => {
    // Add new client to the list
    clients.push(ws);

    console.log('New client connected');

    // Event listener for messages from clients
    ws.on('message', (message) => {
        // Broadcast message to all clients except the sender
        clients.forEach(client => {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
                client.send(message);
            }
        });
    });

    // Event listener for client disconnect
    ws.on('close', () => {
        const index = clients.indexOf(ws);
        if (index !== -1) {
            clients.splice(index, 1);
        }
        console.log('Client disconnected');
    });

    // Error handling
    ws.on('error', (err) => {
        console.error('WebSocket error:', err.message);
    });
});

console.log('WebSocket server running on port 5000');

So basically I am not able to debug that issue. Also share the best way to structure the whole and deploy so that I can share the link of the project as well.

Upvotes: 0

Views: 39

Answers (0)

Related Questions