2015-09-07 32 views
0

第一臺計算機能夠看到每個人進入房間的日誌,但新計算機看不到事先發生的事情。節點聊天服務器:只有第一臺計算機看到所有人

server

var clientMessages = {}; 

socket.on("message", function (data) { 
    var parsed = JSON.parse(data); 
console.log("parsed id " + parsed.id); 
    if (parsed.type === "join") { 
     // A new client has joined. 
     // First, send them all the changes for all the current synths that are in the chat. 
     var jsonstringy = JSON.stringify({ type: "history", value: clientMessages}); 
     socket.send(jsonstringy); 


     // Now create a new record to store all changes sent to this synth. 
     clientMessages[parsed.id] = [parsed]; 
     console.log(clientMessages); 
    } else if (parsed.type === "leave") { 
     delete clientMessages[parsed.id]; 
    } else { 
    clientMessages[parsed.id].push(parsed); 
    } 
}); 

它說推(解析)的線;有時會引發錯誤並使服務器崩潰。

前端位於here

回答

0

您只將數據發送到收到該消息的套接字;你需要做的廣播到所有插座,語法是:

var srv = require('http').createServer().listen(8080); 
var io = require('socket.io')(srv); 

function sendToAll(topic, data) { 
    io.sockets.in(topic).emit(topic, data); // <-- this sends the data to all sockets subscribed to the topic 
} 

當您收到一條消息,記得插座訂閱主題/消息:

socket.join(topic); 
+0

感謝,這是有益的。雖然我沒有使用socket.io。我會嘗試加入message.ids,然後將它們發送給新的客戶端 – mrtunes