I'm working on a project that needs socket handshake session I'm trying to get this code to work, that I got it from https://www.npmjs.com/package/express-socket.io-session
var app = require('express')(),
server = require("http").createServer(app),
io = require("socket.io")(server),
session = require("express-session")({
secret: "my-secret",
resave: true,
saveUninitialized: true
}),
sharedsession = require("express-socket.io-session");
// Attach session
app.use(session);
// Share session with io sockets
io.use(sharedsession(session));
io.on("connection", function(socket) {
// I've add this one...
console.log(socket.handshake.session);
// Accept a login event with user's data
socket.on("login", function(userdata) {
socket.handshake.session.userdata = userdata;
});
socket.on("logout", function(userdata) {
if (socket.handshake.session.userdata) {
delete socket.handshake.session.userdata;
}
});
});
server.listen(3000);
I run it and first I got this
var io = require("socket.io")(server);
^
TypeError: require(...) is not a function
at Object.<anonymous> (/Users/Jack/Root/Sites/Scopone/provaric/server.js:8:30)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
at Function.Module.runMain (module.js:467:10)
at startup (node.js:136:18)
at node.js:963:3
solved adding
io = require("socket.io").listen(server);
and then I got this one
io.use(function(socket, next) {
^
TypeError: io.use is not a function
at Object.<anonymous> (/Users/Jack/Root/Sites/Scopone/provaric/server.js:15:5)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
at Function.Module.runMain (module.js:467:10)
at startup (node.js:136:18)
at node.js:963:3
Any ideas to fix this?
I had the same problem in the same context. Even though your question is up here for a while,I will post my approach.
The whole problem was that i used:
var io = require('socket.io');
But it should be:
var io = require('socket.io')();
Everything else is working without those braces at the end but apparently io.use does not.
Instead of passing the Server I did:
app.io = io;
In /bin/www
app.io.attach(server);
Hope that this is useful to someone.
UPDATE: I use Socket 1.5.2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With