javascriptnode.jswebsocketwschatroom

Why my messages are being displayed many times?


I made a chat room using electron. But when I send a message to the server and from there the message will be displayed to the users for some reason the message is being displayed multiple times. Example: I send -> "hello" the message will be displayed once, when I send a second message ->"Hello server" the message will be display two times, when I sent a third message ->"ok" this message will be displayed three times. The fourth message will be displayed 4 times etc.

this is the renderer.js code:

const ws = new WebSocket("ws://127.0.0.1:5000");

ws.addEventListener('open', function(event){
   ws.send('hello server');
   console.log("data sent");
});

 function send_data(){
  console.log("button clicked");
  ws.send(document.getElementById("input_text").value);

  ws.addEventListener('message', function(event){
  console.log("server send something");
  let mess=event.data;
  console.log(mess);
  update_chat(mess);
});
};
function update_chat(mess){
  const div = document.createElement('div');
  div.classList.add('message');
   div.innerHTML = `okwpegjwpgj said:  ${mess}`;
  document.querySelector('.chat_messages').appendChild(div);
}

this is the server.js code:

const WebSocket = require('ws');
let broadcast_msg;

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

wss.on("connection", ws =>{
  ws.on('message', function incoming(message){
    broadcast_msg=message;
    console.log('received: ', message);
    ws.send(message);
  });
});

console.log("Server is liestening on port " + PORT);

Solution

  • Change your renderer.js file to this:

    const ws = new WebSocket("ws://127.0.0.1:5000");
    
    ws.addEventListener('open', function(event){
       ws.send('hello server');
       console.log("data sent");
    });
    ws.addEventListener('message', function(event){
      console.log("server send something");
      let mess=event.data;
      console.log(mess);
      update_chat(mess);
    });
    
     function send_data(){
      console.log("button clicked");
      ws.send(document.getElementById("input_text").value);
    };
    function update_chat(mess){
      const div = document.createElement('div');
      div.classList.add('message');
       div.innerHTML = `okwpegjwpgj said:  ${mess}`;
      document.querySelector('.chat_messages').appendChild(div);
    }