简体   繁体   English

存储socket.io在全局数组+ Node.js中发出

[英]Storing socket.io emits in global array + Node.js

Is there a way to store all emits of socket.io in a global array so that I can loop through the emits when a new user joins the website and can pickup where the 'canvas drawing' currently is. 有没有一种方法可以将所有socket.io的发射存储在一个全局数组中,以便当新用户加入该网站时可以遍历发射,并可以拾取“画布图形”当前所在的位置。 I want the new user to see what work has already been done and then collaborate on it. 我希望新用户看到已经完成的工作,然后就此进行协作。

Any other ways I could approach towards this? 还有其他方法可以解决吗?

If you just want the emits stored for the duration of the server running, you can simply declare a module level array and push each emit into that array. 如果只希望在服务器运行期间存储发射,则只需声明一个模块级数组并将每个发射推入该数组即可。 Then, at any future time during that server execution, you can consult the array. 然后,在该服务器执行期间的任何将来时间,您都可以查询该阵列。

If, you want the emits stored across server invocations, then you would need to store them to some persistent storage (file, database, etc...). 如果要在服务器调用之间存储发射,则需要将它们存储到某个持久性存储(文件,数据库等)中。

// save incoming data from one particular message
var emitsForSomeMessage = [];

io.on("someMessage", function(data) {
    // save the incoming data for future reference
    emitsForSomeMessage.push(data);
});

Or, if you're trying to store all outgoing .emit() data, then you can override that method and save away what is sent. 或者,如果您尝试存储所有传出的.emit()数据,则可以覆盖该方法并保存发送的内容。

var outgoingEmits = [];
(function() {
    var oldEmit = io.emit;
    io.emit = function(msg, data) {
        outgoingEmits.push({msg: msg, data: data});
        return oldEmit.apply(this, arguments);
    };
})();

Since there are many different messages that may be sent or received, you can add your own logic to decide which messages are saved in the array or not. 由于可能发送或接收许多不同的消息,因此您可以添加自己的逻辑来确定哪些消息保存在阵列中或不保存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM