socket.io icon indicating copy to clipboard operation
socket.io copied to clipboard

Multiple Socket.io connection on page refresh.

Open waqas1991 opened this issue 12 years ago • 3 comments

Hi, I had to display node.js server side log on browser so I used socket.io and tail modules. The code is working fine except one issue. The issue is when first time i visit the page its display correct logs to me on the browser but when refresh the page then logs appears twice then again I refresh the page then it appears three time and so on. Here is my code

logs.ejs

    <% script('/js/socket.io.js') -%>
    <% script('/js/jquery.min.js') -%>

   <script>
    // creates socket on page load

    $(function() {
      var socket = null;
      var streamer = null;
      var socket = io.connect('http://localhost');
      streamer = $('#streamer');

      // outputs a new line to browser for each new line in file
       socket.on('new-data', function(data) {

        var newLine = $('<div>' + data.value + '</div>');
        streamer.append(newLine);
      });
    });
  </script>

 <div id="streamer">
 </div>

app.js

   var app            = express()
 , server = require('http').Server(app)
 , io = require('socket.io')(server)
  server.listen(3000)
  Tail = require('tail').Tail;
  io.sockets.on('connection', function(socket) {   
  tail = new Tail("log.log");    // file to stream

  tail.on('line', function(data) {
    return io.sockets.emit('new-data', {
        channel: 'stdout',
        value: data
     });
   });
 });

I dont know but I think its creating multiple connections on page refresh.

waqas1991 avatar Aug 05 '14 06:08 waqas1991

I am having the same issue. I am running socket.io version 1.0.2. Any updates on what maybe causing this issue?

PS I have not posted the code as I am having some formatting issues pasting code here.

nikhiljgeorge avatar Aug 12 '14 06:08 nikhiljgeorge

first of all dont recreate event listener, just one time you must define on('connection') method.
secound : don't forget to use forceNew parameter in io intitialize third: don't use io creational in router handler (expressjs or any webserver...)

arash-hacker avatar Sep 30 '18 17:09 arash-hacker

forceNew

I used this option also but still not working. I Used socket io version 4.5.1

kamleshdarteweb avatar Aug 10 '22 05:08 kamleshdarteweb