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.