第一台计算机能够看到每个人进入房间的日志,但是新的计算机看不到之前发生了什么。
服务器 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);
}
});
表示push(parsed);有时会抛出错误并使服务器崩溃。
前端位于此处。
您只向接收消息的套接字发送数据;您需要对所有套接字进行广播,语法为:
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);