I'm currently working on a real-time chat using Socket.IO, but I've encountered a major issue. The aim is to allow users to log in, select another connected user, and start chatting...
var http = require('http'),
fs = require('fs'),
path = require('path'),
io,
server;
var PORT = 3000,
HOST = '127.0.0.1';
server = http.createServer( function ( request, response ) {
var filePath = '.' + request.url,
extName,
contentType;
if (filePath == './') {
filePath = './index.html';
}
extName = path.extname(filePath);
contentType = 'text/html';
switch ( extName ) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
fs.exists( filePath, function ( exists ) {
if ( exists ) {
fs.readFile( filePath, function ( error, content ) {
if ( error ) {
response.writeHead( 500 );
response.end();
}
else {
response.writeHead( 200, { 'Content-Type': contentType });
response.end( content, 'utf-8' );
}
});
}
else {
response.writeHead( 404 );
response.end();
}
});
}).listen( PORT, HOST );
io = require('socket.io').listen( server );
var Users = [ ]; // List of users
io.sockets.on('connection', function ( socket ) {
var user = { }; // The user
socket.on('newUser', function ( data ) {
user.userName = data.name, // Selected name
user.userId = socket.id; // The socket id
Users.push( user );
socket.emit('me', user); // Emit the user object
socket.emit('userList', { users : Users }); // Emit the user list
});
socket.on('disconnect', function () {
Users.remove( user ); // Delete from the user list
socket.emit('userList', { users : Users }); // emit again the user list for refresh
});
socket.on('clientMessage', function ( data ) {
io.sockets.socket(data.to).emit('newMessage', {
// data.to is the socket ID that a message is sent
"from" : data.from,
"message" : data.message,
"date" : new Date()
});
});
});
The current problem is that when a user opens multiple tabs, each tab receives a different socket.id from the server. This causes messages not to be synchronized across all tabs.
I am looking for solutions to maintain the same socket.id for a logged-in user across all tabs so that messages can be displayed consistently.
Any suggestions or solutions?