G
G
gleendo2017-08-24 15:59:17
Node.js
gleendo, 2017-08-24 15:59:17

Why is the message not being sent to all clients (socket.io)?

The logic is this: Clients are connected. One of the clients clicks to introduce himself. Enters your name. The message "Hello {{ Username }}" is displayed to this client. All other clients receive the message "Hi from {{ Username }}".
But when sending a message (After the client introduces himself), only the last connected client receives it, although, according to the idea, everyone except the sender (broadcast) should receive it.
What could be the problem? And how to solve it?
But this part doesn't work at all:

client.emit("hello", {
  hello: `Привет ${data}!`
});

// server.js
const app = require("express")();
const http = require("http").Server(app);
const io = require("socket.io")(http);

app.use(require("express").static(__dirname + "/public"));

io.on("connection", client => {
  client.on("message", data => {
    console.log(data);

    client.emit("hello", {
      hello: `Привет ${data}!`
    });

    client.broadcast.emit("hello", {
      hello: `Привет от ${data}!`
    });
  });
});

http.listen(3000);

// client.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="/socket.io/socket.io.js"></script>
</head>
<body>
  <button>Представьтесь</button>

  <script>
    const socket = io.connect("http://localhost:3000");

    socket.on("hello", data => {
      alert(data.hello);
    });

    const button = document.querySelector("button");

    button.addEventListener("click", event => {
      const name = prompt("Как вас зовут?", "Гость");

      if (name) {
        socket.emit("message", name);
      }
    }, false);
  </script>
</body>
</html>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
de1m, 2017-08-24
@de1m

It didn’t work for me with broadcast either, try this. Here is the complete example

A
Abcdefgk, 2017-08-24
@Abcdefgk

And try to erase

client.emit("hello", {
      hello: `Привет ${data}!`
    });

Right, I just figured out the "rooms & namespace" system in socket.io - and, as it turned out, it works so wonderfully there that I now don't even believe that something doesn't work there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question