我正在使用 NodeJS 创建一种将图片一次发送到多个显示器的方法,目前我的代码有以下语句:
var $ = require('jQuery');
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app, { log:false });
var fs = require('fs');
var Server = {
server_address : "XXX.XXX.XXX.XXX", // The server address
playing_now : Object // The playlist that are being synced
};
var Client = {
clients : Object
};
app.listen(1337);
console.log("App is running on port 1337...");
function handler(request, response) {
var ip_address = null;
try{ ip_address = request.header('x-forwarded-for'); }
catch(error){ ip_address = request.connection.remoteAddress; }
Client.clients[ip_address] = "X";
fs.readFile(__dirname + '/index.html', function (err, data) {
if (err) {
response.writeHead(500);
return response.end('Error loading index.html');
}
response.writeHead(200);
response.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.on("RequestPlaylist", function(json){
Client.clients[json["Address"]] = json["PlayList"];
if(typeof Server.playing_now[json["PlayList"]] === 'undefined'){
$.ajax({
url : "http://" + Server.server_address + "/buildPlayList.php",
type : "GET",
dataType : "jsonp",
method : "GET",
data : {RemoteIP : json["Address"], Name : json["PlayList"]}
}).done(function(playlistJSON){
console.log("________________________________________");
console.log("Done");
console.log(Server.playing_now);
Server.playing_now[playlistJSON["playName"]] = playlistJSON;
console.log(Server.playing_now);
console.log("________________________________________");
})
}else{
console.log("________________________________________");
console.log("Redirect");
console.log(Server.playing_now);
console.log("________________________________________");
}
});
});
当新客户端连接时,我将它的 IP 地址存储在 Client.clients 上,当我获得包含图像 URL 的 json 时,我将其存储在 Server.playing_now 上。
问题是,当我输出 Server.playing_now 时,它包含了 Client.clients 的内容:
Done
{ [Function: Object] 'XXX.XXX.XXX.XXX': 'Default Media' }
{ [Function: Object]
'XXX.XXX.XXX.XXX': 'Default Media',
'Default Media':
{ '1':
{ json: [Object],
duration: '5',
name: 'Slideshow',
type: 'Image',
sync: '1',
callback: 'jQuery17207063492417801172_1377555709748' },
playName: 'Default Media' } }
如果它再次尝试获取数据,结果如下:
Redirect
{ [Function: Object]
'105.102.15.234': 'Default Media',
'Default Media':
{ '1':
{ json: [Object],
duration: '5',
name: 'Entrenamiento PL',
type: 'Image',
sync: '1',
callback: 'jQuery17207063492417801172_1377555709748' },
playName: 'Default Media' } }
在我的代码中,我没有合并这两个对象,如果我注释掉 Client 对象,它确实只返回 Server.playing_now 的内容。
知道会发生什么吗?或者这种行为是预期的?