在socket.io事件中使用回调是否安全?

时间:2018-04-30 06:46:52

标签: node.js socket.io

在使用Node.js和Socket.io构建我的应用程序时,我一直在使用回调将数据发送回向服务器发出请求的客户端。

在测试期间,我错误地从客户端发送了一个不包含回调的请求。这会在服务器上触发警告消息:

(node:67072) UnhandledPromiseRejectionWarning: TypeError: callback is not a function
    at Socket.socket.on (server.js:247:9)
    at Socket.emit (events.js:127:13)
    at node_modules/socket.io/lib/socket.js:527:12
    at process._tickCallback (internal/process/next_tick.js:150:11)
(node:67072) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 8)
(node:67072) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我的注意力是关于未来未终止Node.js流程的未处理承诺拒绝的最后DeprecationWarning。如果发生这种情况,似乎通过简单地在没有回调的情况下发出易受攻击的事件来使任何使用Socket.io回调的Node.js程序崩溃是微不足道的。

据我了解,防止这种情况的唯一方法是确保在使用之前定义回调:

socket.on('event', (params, callback) => {
    if (typeof callback !== 'function') { return null }

    /* do stuff */

    return callback(response)
}

或者,避免完全使用回调,只通过emit将数据发送回客户端 - 将数据发送给他们正在侦听的事件。

我对此的理解是正确的,还是我完全偏离了这里?

0 个答案:

没有答案
相关问题