【问题标题】:SocketIO - processing data before broadcastingSocketIO - 在广播之前处理数据
【发布时间】:2014-11-26 18:10:36
【问题描述】:

我目前遇到了一个小型 Node.JS 应用程序的问题。它与例如 Socket.IO 示例聊天应用程序极为相似:每当用户向服务器发送数据时,我都需要处理数据,然后将其广播给所有用户。但是,处理数据的方式取决于接收数据的用户。我尝试为每个套接字更改 Socket#emit 方法(以便在发送数据之前处理数据),但广播不使用它。有什么办法可以解决这个问题吗?

提前致谢。


编辑

这是我尝试过的():

var io = require('socket.io');

io.use(function(socket, next) {
    var old_emit = socket.emit;

    socket.emit = function() {
        // do something with the data (arguments[1] in this case)
        // the processing of the data depends on a value that is
        // unique to each connection, and can't be sent over to the client

        old_emit.apply(socket, arguments);
    }
});

我尝试了上面的代码,因为最初我认为广播会为每个连接在其他地方调用emit

【问题讨论】:

  • 你有没有尝试过?贴出代码有助于我们理解
  • pmverma,正如我在问题中所说,我已经尝试重载 Socket#emit 方法。我会尝试添加更多信息。

标签: node.js socket.io


【解决方案1】:

我不确定你想做什么, 没有任何类似“io()”的函数。你做错了。

顺便说一句,处理数据。 来自示例聊天应用程序,

// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {

 //call a function which you want to process data
 var newData = messageProcessingFunc(data);
//and then broadcast it.

 // we tell the client to execute 'new message'
 socket.broadcast.emit('new message', {
    username: socket.username,
    message: newData 
    });
});

【讨论】:

  • 我很抱歉。我的意思是使用io.use,它向socket.io 添加了一个中间件。而且这段代码 sn-p 对我不起作用,因为消息处理功能取决于连接到服务器的每个用户所独有的数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-20
  • 2020-11-05
  • 1970-01-01
相关资源
最近更新 更多