我做了一个简单的实时访客计数器。
你可以从this repository下载。
发生的情况是,服务器上的disconnect事件(即使在浏览器关闭之后)永远不会触发。
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 );
});发布于 2012-04-27 07:02:44
将你的on disconnect代码放在你的on connect块中,然后像这样编辑它:
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
});
});
});通过这种方式,您可以检测到特定的套接字(特别是传递给匿名函数的套接字,该函数在连接时运行)何时断开连接。
发布于 2015-09-24 11:25:49
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事件在每个套接字中只触发一次。
发布于 2017-02-24 05:45:47
以防其他人犯下这个愚蠢的错误:确保您定义的任何套接字中间件在最后调用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");
});
});https://stackoverflow.com/questions/10342548
复制相似问题