Call Counter Socket.io

Asked

Viewed 634 times

1

Well, here’s the thing I have the following code in my app.js of my project, which I picked up 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);
   });
 });

Regarding HTML, I have it as follows:

 <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 will increase, however when someone leaves, the visits do not decrease, that is it is necessary to give F5, so that they say the real visits again. How can I do, so that when "disconnect" from the site, the visits, are decreasing soon. I tried to touch the socket.broadcoast, but I could not.

Thank you.

1 answer

1


You must issue an event with the same name (it can also be with another but in this context it is more indicated to be with the same), since your client side has no delegated event for when it receives an issuance call message nothing will happen, changes the next on the server side:

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

If you want to keep the name of the issue "message" on the part of 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;
});
...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.