I believe this socket.io
API is deprecated. The solution would be to change its use
of the method Server.prototype.set
by Server.prototype.use
, which will plant a middleware like those of express.
There is an updated version of the examples from Caio Ribeiro Pereira's book.
I think this example
show what you're trying to do, using Server.prototype.use
:
I found an article of socket.io
explaining the differences since version 0.9,
specifically with regard to authentication, I suggest you take a look at here .
Your code should work with this small change from set
to use
:
io.use(function(socket, next) {
var data = socket.request;
cookieSec(data, {}, function(err) {
var sessionID = data.signedCookies[KEY];
SesMemStore.get(sessionID, function(err, session) {
if (err || !session) {
return next(new Error('acesso negado'));
} else {
socket.handshake.session = session;
return next();
}
});
});
});
From socket.io
documentation, translated freely into Portuguese:
Namespace # use (fn: Function): Namespace
Register a middleware; a function that is executed for every connection ( Socket
) that arrives and receives as parameters the socket and a function to optionally execute the next middleware
registered.
Here, Namespace#use(fn:Function):Namespace
, means that this is a method on the Namespace
class, which takes a function as argument and returns a Namespace
, for chaining. It is the default to return this
to be able to chain methods (another example would be superagent
: request.get(url).query(query).end(fn);
).
This may seem confusing, because the io
object in your code is an instance of the Server
class, not the Namespace
class. The idea is that you can create multiple Namespace
objects, just like you can create multiple Router
objects in express
4, each with its own set of handlers and middlewares.
By default, Server.prototype.use
will call Namespace.prototype.use
over Namespace
default, which handles connections to /
. This is similar to the relationship between Application
and Router
of express
.