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.