简体   繁体   中英

WebSocket connection.send only fires once

I have a simple websocket chat app consisting of three files: server.js , index.html , and client.js . The html is two input boxes and a send button, but the send button stops working after the first click. I know the event handler is not the issue because it consistently works if I remove connection.send . Here's the code:

server.js


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

wss.on('connection', (ws) => {
  console.log("New connection");

  ws.on('message', (data) => {
    console.log(`New message: ${data}`)
    wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(data);
      }
    });
  });
});

client.js

 
connection.onopen = (event) => {
  console.log("WebSocket is open now.");
};

connection.onclose = (event) => {
  console.log("WebSocket is closed now.");
};

connection.onerror = (event) => {
  console.error("WebSocket error observed:", event);
};

connection.onmessage = (event) => {
  const chat = document.querySelector('.chat');
  chat.innerHTML += event.data;
}

const button = document.querySelector('#send');
button.addEventListener('click', () => {
  console.log('click');
  const name = document.querySelector('#name');
  const message = document.querySelector('#message');
  const data = `<p>${name.value}: ${message.value}</p>`

  connection.send(data); // Removing this line makes it work

  name.value = "";
  message.value = "";
})

index.html

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Index</title>
</head>
<body>
  <div class="chat">
    <input type="text" placeholder="name" id="name">
    <input type="text" placeholder="message" id="message">
    <button id="send">Send</button>
  </div>
  <script src="client.js"></script>
</body>
</html>

When you do chat.innerHTML += event.data , you make a new button that doesn't have the click event listener.

You can make a separate div to add your extra stuff, or add the click event listener every time you add stuff, or add the extra stuff using appendChild() instead of innerHTML .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM