我正在使用 Socket.IO,但我发现了一个大问题。我正在尝试进行实时聊天:一个用户登录,选择另一个连接的用户并交谈,所以(...)
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()
});
});
});
这就是问题所在;一些用户连接,服务器分配一个 id,(socket.id),但如果同一个用户在同一个导航器中打开更多选项卡,socket.id 将更改,因此用户将不会在其他选项卡中收到该消息。
我想为某些登录用户打开的所有选项卡存储相同的 socket.id;因此,如果该用户收到任何消息,将显示在所有选项卡中。
¿ 解决方案?