我做了一个简单的实时访客计数器。
您可以从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 );
});
答案 0 :(得分:50)
将你的断开连接代码放在你的连接块中并稍微编辑它:
io.sockets.on('connection', function (socket) {
count++;
io.sockets.emit('count', {
number: count
});
socket.on('disconnect', function () {
console.log('DISCONNESSO!!! ');
count--;
io.sockets.emit('count', {
number: count
});
});
});
通过这种方式,您可以检测到特定套接字(特别是传递给在连接上运行的匿名函数的套接字)何时断开连接。
答案 1 :(得分:3)
从Socket.IO 1.0 io.engine.clientsCount
属性可用。此属性会告诉您应用当前有多少个打开的连接。
io.sockets.on('connection', function (socket) {
io.sockets.emit('count', {
number: io.engine.clientsCount
});
socket.once('disconnect', function () {
io.sockets.emit('count', {
number: io.engine.clientsCount
});
});
});
注意:使用.once
代替.on
,监听器将自动从socket
中删除,这对我们现在有利,因为每个插槽只会触发一次disconnect事件。
答案 2 :(得分:0)
以防万一其他人犯了这个愚蠢的错误:确保你定义的任何套接字中间件最后调用next()
,否则就不会运行其他套接字处理程序。
// make sure to call next() at the end or...
io.use(function (socket, next) {
console.log(socket.id, "connection middleware");
next(); // don't forget this!
});
// ...none of the following will run:
io.use(function (socket, next) {
console.log(socket.id, "second middleware");
next(); // don't forget this either!
});
io.on("connection", function (socket) {
console.log(socket.id, "connection event");
socket.once("disconnect", function () {
console.log(socket.id, "disconnected");
});
});