Reputation: 673
I'm using this memcached package and I'm trying to get data from my server that store my PHP sessions with memcache. Whenever someone enters my website, a value is stored in the variable $_SESSION["user"]
(used to chat) and I want to get that values to use with socket.io
(to define who is online and send messages, regardless of the server), because if I am connected to server 2
, whoever is on server 1
can't see me online or send me messages, so, I did:
var express = require("express"),
app = express(),
http = require("http").Server(app),
io = require("socket.io")(http),
Memcached = require("memcached"),
users = {};
// app.use(express.static(__dirname + "/scripts"));
io.on("connection", function(socket) {
var mem = new Memcached("privateipofmymemcachedserver:11211");
mem.get("user", function(err, data) {
if(err) {
return console.error(err);
}
if(data === false) {
return console.error("Data no found!");
}
console.log("Data: " + data);
});
// From client, sended when $(document).ready()
socket.on("connected", function(data) {
socket.user = data.user;
if(!users[socket.user]) {
users[socket.user] = new Set();
}
users[socket.user].add(socket);
updateUsers();
});
// To update online users list
function updateUsers() {
io.emit("users", Object.keys(users));
}
});
var port = Number(process.env.PORT || 8000);
http.listen(port, function() {
console.log("Server running on 8000!");
});
But, when I run the code and go to console, the only thing that returns is:
Data: undefined
Data: undefined
Data: undefined
How can I "fix" it? Or is there any better way to do this without involving PHP sessions, just with the socket itself and its functions? Using socket or express cookies, perhaps? I also read about Redis, if it is a good option, how could I adapt my code to use it?
Upvotes: 0
Views: 895
Reputation: 19385
If you are using using elastic beanstalk, look into enabling sticky sessions on your load balancer. This will fix your issue.. There is also a way of doing this with a socket.io adapter but socket.io-memcached lib is not maintained anymore it seems. I would recommend you switch to redis if you want to use an adapter. – mkhanoyan
Upvotes: 1