javascript - NodeJS & Socket.IO : Emit a request event and get the response, 我应该何时/何地绑定(bind)监听器?

标签 javascript node.js socket.io

我目前想知道在这种情况下什么是最佳编程实践:

假设我已将客户端连接到我的服务器。这个客户端要求服务器使用 auth 事件和他的用户名进行身份验证。

socket = io();
socket.emit('auth', "John");

在这个简单的例子中,服务器响应一个带有用户 ID 的 auth_succeed 事件。

io.on('connection', function(socket) {
    socket.on('auth', function(username) {
        socket.emit('auth_succeed', id);
    }
}

所以我的问题是,我应该在何时何地为客户端中的 auth_succeed 事件绑定(bind)监听器? 我有两种方法:

在发射之前,我想这确保了响应事件将始终得到正确处理,但会导致一些意大利面条代码。例如:

socket = io();
socket.on('auth_succeed', function(id){
    //Do some post-auth stuff here
}); 
socket.emit('auth', "John");

或者在发射之后,这会导致更清晰的代码,但我再次猜测,如果发送速度足够快,可能会错过事件。例如:

socket = io();
socket.emit('auth', "John");
socket.on('auth_succeed', function(id){
    //Do some post-auth stuff here
}); 

你对这个问题有什么看法?

最佳答案

由于 emit 的响应应该是异步的,而客户端 JS 本质上是同步的,因此 socket.on('auth_succeed' 绑定(bind)将在 的回调之前发生auth 事件。


以下流程将在客户端发生...

// EXECUTION SCOPE BEGINS
...
// this will send a message to the server
// the message and/or response will be sent asynchronously
socket.emit('auth', 'John'); 
// so your code will continue before you get anything from the server

//which means the following binding will happen before any response to the above emit
socket.on('auth_succeed', function(id){
  //... handle message from server ...
});
...
// EXECUTION SCOPE ENDS

在封闭范围/函数完成执行后的某个时间,将引发“auth_succeed”事件。


您可能还想考虑分解您的事件处理程序...

socket.on('auth_succeed', onAuthSucceed.bind(null, socket));
socket.emit('auth', 'john');

// ... elsewhere ...

function onAuthSucceed(socket, id) {
  // handle message from server
}

无论您选择先绑定(bind)还是先发射,这都会减少绑定(bind)和信号事件的噪音。

通过让函数 require 它需要的任何东西,并为事件使用绑定(bind),所讨论的方法可以在单独的文件/模块中,并且更容易单独测试。

关于javascript - NodeJS & Socket.IO : Emit a request event and get the response, 我应该何时/何地绑定(bind)监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27720384/

相关文章:

node.js - Electron :无法读取未定义的属性 'send'

javascript - 使用 q.js Promise 时出现问题

node.js - 通过 Cloudflare 为 socket.io 提供 HTTPS

php - 仅浏览器端的 Socket.io?

websocket - 使用 Phoenix Channels 跨源

javascript - php/mysql 动态下拉菜单的 AJAX RETURN 帮助

javascript - 将错误返回到 Node.js 中的回调

node.js - sails.js - 我如何在模型 Hook beforeCreate 中访问 session 数据

javascript - javascript中括号内的大括号是什么意思?

javascript - 重新加载后如何保留页面中的数据?