Sunday 11 June 2017

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>



via Murlidhar Fichadia

No comments:

Post a Comment