简体   繁体   中英

Emitting data to all the users in given channel - Nodejs (Socket.io)

I have a very simple scenario. Where all users are subscribers and API data call is a Publisher. I send same data to all the connected users to X channel.

I am aware of three functions available in socket.io

socket.emit('example', data);
io.sockets.emit('example', data);
socket.broadcast.emit('example', data);

In my example, I am using sockets to push real-time data on the client-side the issue I am facing is that if more than 1 user joins particular channel then data is sent to all N times.

I am sending some data every N seconds. if 1 user is joined then everything works perfectly fine. because x data is sent to single user connected. but if 2 users are connected to the same channel and if I send x data every 10 seconds I see speed of sending is halved, that is every 5 seconds data is sent. If I open 10 tabs (meaning 10 users connected) and if I am sending data every 10 seconds to all the connected users. I see data sent every 1 second to all the users.

Because my application is pushing real-time data from API to all the users and not sending message of one user to all other connected users. I guess I need different approach. That is, I dont want any user to listen any other users but simply receive the same data that everyone is receiving.

How do I achieve this?

Below is my code

server-side code

var app = require('express')();
var http = require('http').Server(app);
var httpk = require('http');
var io = require('socket.io')(http);
var nsp = io.of('/channel1');

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

nsp.on('connection', function(socket){

  nsp.emit('live', 'Welcome User!');

  function test()
  {
    httpk.get("api-to-url", function(res) {
        var body = ''; 
        res.on('data', function(data){
            body += data;
        });
        res.on('end', function() {
            var parsed = JSON.parse(body);
            console.log(parsed.johndoe.bid_price);
            nsp.emit('live', parsed.johndoe.bid_price);
        });
    });
  }

  setInterval(test,10000);

  socket.on('disconnect', function(){
    console.log('1 user disconnected');
  });

});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

client-side code

<!doctype html>
<html>
  <head>
    <title>Live App</title>
    <style>
      body { font: 26px Helvetica, Arial; font-weight:bold;}

      #livez { text-align: center;}
    </style>
  </head>
  <body>
    <p id="livez"></p>


    <script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>

<script>
  $(function () {
    var socket = io('/channel1');

     socket.on('live', function(msg){
    $('#livez').text(msg);
    });
  });

</script>
  </body>
</html>

From this:

  nsp.on('connection', function(socket){

  nsp.emit('live', 'Welcome User!');

  function test()
  {
    httpk.get("api-to-url", function(res) {
        var body = ''; 
        res.on('data', function(data){
            body += data;
        });
        res.on('end', function() {
            var parsed = JSON.parse(body);
            console.log(parsed.johndoe.bid_price);
            nsp.emit('live', parsed.johndoe.bid_price);
        });
    });
  }

  setInterval(test,10000);

  socket.on('disconnect', function(){
    console.log('1 user disconnected');
  });

});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

to this:

 function test()
  {
    httpk.get("api-to-url", function(res) {
        var body = ''; 
        res.on('data', function(data){
            body += data;
        });
        res.on('end', function() {
            var parsed = JSON.parse(body);
            console.log(parsed.johndoe.bid_price);
            nsp.emit('live', parsed.johndoe.bid_price);
        });
    });
  }



 setInterval(test,10000);

nsp.on('connection', function(socket){

  nsp.emit('live', 'Welcome User!');

  socket.on('disconnect', function(){
    console.log('1 user disconnected');
  });

});

Because your setInterval is locally set within each client connection you will duplicate this causing the interval to be called multiple times. Instead of having it locally you need to make it so that it's configured outside so it's agnostic to the client signing onto the page.

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