나는 간단한 실시간 방문자 카운터를 만들었습니다.socket.io : 연결 해제 이벤트가 실행되지 않습니다.
this repository에서 다운로드 할 수 있습니다.
서버에서 브라우저 종료 후에도 연결 끊김 이벤트가 발생하지 않습니다.
server.js은 다음과 같습니다 클라이언트에서
(function() {
var app, count, express, io;
express = require('express');
io = require('socket.io');
app = module.exports = express.createServer();
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(require('stylus').middleware({
src: __dirname + '/public'
}));
app.use(app.router);
return app.use(express.static(__dirname + '/public'));
});
app.configure('development', function() {
return app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
app.configure('production', function() {
return app.use(express.errorHandler());
});
io = require('socket.io').listen(app);
count = 0;
io.sockets.on('connection', function (socket) {
count++;
io.sockets.emit('count', {
number: count
});
});
io.sockets.on('disconnect', function() {
console.log('DISCONNESSO!!! ');
count--;
io.sockets.emit('count', {
number: count
});
});
app.get('/', function (req, res) {
return res.render('index', {
title: 'node.js express socket.io counter'
});
});
if (!module.parent) {
app.listen(10927);
console.log("Express server listening on port %d", app.address().port);
}
}).call(this);
스크립트입니다
script(type='text/javascript')
var socket = io.connect();
socket.on('count', function (data) {
$('#count').html(data.number);
});
위에서 socket.on을 작성했는지 확인 했습니까? – swiecki
완벽 함, 이제는 정상적으로 작동 함 –
FYI, 전송에 xhr 폴링을 사용하는 경우 연결 해제 전에 상당한 시간이 걸릴 수 있습니다. –