简体   繁体   中英

Can't receive broadcasted event in client using socket.io

I'm trying to render some data on active.ejs which has a socket that is listening for the event users . The event users is emitted as a broadcast by index.js .

I have a console.log("do you go here") in my socket listener function in active.ejs . However, it never logs "do you go here" in socket.on so that means somehow the broadcast emitted by index.js isn't received by active.ejs . How do I get it to receive it?

index.js

var io = socket(server);
io.on('connection', function(socket){
  count++;
  socket.broadcast.emit('users', socket.handshake.query);
});

active.ejs

    ..html boilerplate
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="http://localhost:4000/socket.io/socket.io.js"></script>
  </head>
  <body>
    <p>
      Welcome,
      <%= user_info.uri %>
    </p>
    <div id="active"></div>
    <script>
    var socket = io.connect('http://localhost:4000/tune-in', {query: <%- JSON.stringify(user_info) %>});
    var active = document.getElementById('active');

    // Listening for events on socket
    socket.on('users', function(data){
      console.log('do you go here');
      active.innerHTML += "<p><em>" + data.display_name + " is connected" + "</em></p>";
    });
    </script>
  </body>
</html>

Your code socket.broadcast.emit('users', socket.handshake.query); does exactly what it should - sends event to all clients except the client that has just connected.
You may want to use io.emit('users', socket.handshake.query) instead.

EDITED:

Add the namespace to the server:

var io = socket(server);
io.of('/tune-in').on('connection', function(socket){
  count++;
  socket.broadcast.emit('users', socket.handshake.query);
});

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