Socket.io Visitor Counter

1

Well, this is the following I have the following code in my app.js from my project, which I took on the internet to study:

 // Servidor: app.js
 // Iniciando servidor HTTP
 var app = require('http').createServer(index)
   , io = require('socket.io').listen(app)
   , fs = require('fs')
 ;
 app.listen(3000, function() {
   console.log("Servidor rodando!");
 });
 function index(req, res){
   fs.readFile(__dirname + '/index.html', function(err, data){
 res.writeHead(200);
     res.end(data);
   });
 };
 // Iniciando Socket.IO
 var visitas = 0;
 // Evento connection ocorre quando entra um novo usuário.
 io.on('connection', function(socket){
   // Incrementa o total de visitas no site.
   visitas++;
   // Envia o total de visitas para o novo usuário.
   socket.emit('visits', visitas);
   // Envia o total de visitas para os demais usuários.
   socket.broadcast.emit('visits', visitas);
   // Evento disconnect ocorre quando sai um usuário.
   socket.on('disconnect', function(){
     visitas--;
     // Atualiza o total de visitas para os demais usuários.
     socket.broadcast.emit('message', visitas);
   });
 });

For HTML, I have this:

 <html>
   <head>
     <script src=/socket.io/socket.io.js></script>
     <script>
     var socket = io('http://151.80.152.6:3000');
     socket.on('visits', function(visitas){
       document.getElementById('visitas').innerHTML = visitas;
     });
     </script>
   </head>
   <body>
     <p>Contador de visitas online com Socket.io</p>
     <p>Número de visitas: <span id="visitas">0</span></p>
   </body>
 </html>

My problem is this: When someone enters the site, the visits are increasing, but when someone leaves, the visits do not decrease, ie it is necessary to give f5, so that it returns to say the actual visits. How can I do it, so that by "disconnecting" from the site, the visits, are diminishing soon. I tried to play socket.broadcoast, but I could not.

Thank you.

    
asked by anonymous 22.03.2017 / 03:52

1 answer

1

You must issue an event with the same name (it can also be with another one, but in this context it is more appropriate to be with it), since your client side has no delegated event for when it receives an issue called message nothing will happen, change the following from the server side:

...
socket.on('disconnect', function(){
   visitas--;
   socket.broadcast.emit('visits', visitas); // <-- Alterar aqui
});
...

If you want to remain with the name of the issue " message " by the server you must then prepare the client side to receive it:

...
socket.on('visits', function(visitas){
    document.getElementById('visitas').innerHTML = visitas;
});
socket.on('message', function(visitas){
    document.getElementById('visitas').innerHTML = visitas;
});
...
    
22.03.2017 / 10:36