My application works this way :
- The user logins to the website
- JavaScript connect to the Socket.IO server, and transmit PHPSESSID
- Socket.IO use PHPSESSID to connect to database and then get
user_id
- With
user_id
we connect one more time to database to getuser_place
- The user is then connected to the room
user_place
and can talk with other people here
The thing is that user_place
can changes via, for example, another php script.
So when it changes, I need to tell the current socket io connection to fetch new “user_place” from database, so it can leave the current room and connect to the new one.
How can I achieve this ?
I had 2 guesses :
- When the php script is executed, connect to the existing Socket.IO connection and execute code like
client.on('update_place'), function() {}
. The thing is that I don't know how to connect to an existing connection (is it possible ?) - Has a setTimeout() function checking constatly on the database if “user_place” has changed or not (but perfs will be terrible)
Here is some simplified code of the node server :
io.sockets.on('connection', function(client) {
var user_place;
// Read client cookies
if(client.handshake.headers['cookie']) {
var cookies = cookie.parse(client.handshake.headers['cookie']);
}
// If cookies exist, connect to database and get “user_place”
if(cookies) {
connection.query("SELECT session_value, session_time FROM sessions WHERE session_id = ?", [cookies.PHPSESSID], function(err, rows, fields) {
if(rows[0]) {
var session_value_json = JSON.parse(atob(rows[0].session_value));
user_id = session_value.user_id;
if(user_id) {
connection.query( "SELECT place FROM users WHERE id = ?", [user_id], function(err, rows, fields) {
// Set data user_place
user_place = rows[0].user_place;
// Join the room
client.join(user_place);
});
}
}
});
}
// Chatting...
client.on('message', function (data) {
io.sockets.in(user_place).emit('message', {
user_id : user_id,
message_content : data.message
}
);
});
});